package cn.hznc.controller.service.inventory;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.configuration.MinioHelper;
import cn.hznc.configuration.SystemInit;
import cn.hznc.constant.CommonConstant;
import cn.hznc.constant.InventoryStatusEnum;
import cn.hznc.constant.WarehouseConstant;
import cn.hznc.controller.service.inventory.logic.SafetyInventoryDo;
import cn.hznc.controller.service.inventory.logic.SafetyInventoryLogic;
import cn.hznc.controller.service.toollife.ToolLieService;
import cn.hznc.controller.uploadfilestrategy.Context;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.entity.common.WarehouseImportEntity;
import cn.hznc.domain.request.inventory.*;
import cn.hznc.domain.request.schedule.ToolReturnIndexReq;
import cn.hznc.domain.request.schedule.ToolReturnReq;
import cn.hznc.domain.request.toolAnalyze.ToolConsumptionandUsageAnalysisReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.dto.FirstStockImport;
import cn.hznc.dto.IToolCabinetStockImport;
import cn.hznc.dto.ToolConnectImport;
import cn.hznc.dto.ToolConnectSimpleImport;
import cn.hznc.exception.*;
import cn.hznc.mapper.*;
import cn.hznc.repository.*;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.UUIDUtil;
import cn.hznc.vo.*;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @Author：Administrator
 * @Date：2023/4/2 15:31
 */
@Service
@Slf4j
public class InventoryLocationService {

    private static final List<String> toolWarehouseTypeList;

    private static final List<String> assemblyToolWarehouseTypeList;

    static {
        toolWarehouseTypeList = Arrays.asList("A001", "A002");
        assemblyToolWarehouseTypeList = Arrays.asList("A003", "A004", "A005", "A007");
    }

    @Resource
    private ToolInventoryLocationRespository toolInventoryLocationRespository;

    @Resource
    private ToolInventoryLocationMapper toolInventoryLocationMapper;

    @Resource
    private InventoryLocationRespository inventoryLocationRespository;

    @Resource
    private ToolPartRespository toolPartRespository;

    @Resource
    private ToolForkRespository toolForkRespository;

    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;

    @Resource
    private WarehouseRespository warehouseRespository;

    @Resource
    private WarehouseItemRepository warehouseItemRepository;

    @Resource
    private AssemblyToolInventoryRepository assemblyToolInventoryRepository;

    @Resource
    private AssemblyToolInventoryMapper assemblyToolInventoryMapper;

    @Resource
    private ToolPartMapper toolPartMapper;

    @Resource
    private WarehouseMapper warehouseMapper;

    @Resource
    private ToolConnectMapper toolConnectMapper;

    @Resource
    private ToolLifeMapper toolLifeMapper;

    @Autowired
    private ToolPartService toolPartService;

    @Autowired
    private EntryExitRecordService entryExitRecordService;

    @Resource
    private TypeItemRepository typeItemRepository;

    @Resource
    private MachineToolTaskRespository machineToolTaskRespository;

    @Resource
    private ConfigurationMapper configurationMapper;

    @Autowired
    private MinioHelper minioHelper;

    @Autowired
    private MinioProp minioProp;

    @Autowired
    private ToolLieService toolLieService;

    @Resource
    private ToolParamCacheRepository toolParamCacheRepository;

    @Resource
    private EntryExitRecordMapper entryExitRecordMapper;


    private static Lock lock = new ReentrantLock();

    private static final ConcurrentHashMap<String, String> warehouseTypeMap = new ConcurrentHashMap<>();

    static {
        warehouseTypeMap.put("A001" , "一级刀具库");
        warehouseTypeMap.put("A002" , "智能刀具库");
        warehouseTypeMap.put("A003" , "组刀室");
        warehouseTypeMap.put("A004" , "线边柜");
        warehouseTypeMap.put("A005" , "机床刀具柜");
        warehouseTypeMap.put("A006" , "报废区");
        warehouseTypeMap.put("A007" , "备刀区");
    }

    public List<InventoryILocationReq> showInventoryLocationMessage(Integer warehouseId, Integer flag) {

        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectByWarehouseId(warehouseId);
        if (CollectionUtil.isNotEmpty(inventoryLocationEntities)) {
            if (ObjectUtil.isNull(flag)) {
                inventoryLocationEntities.forEach(inventoryLocationEntity -> {
                    Integer number = inventoryLocationRespository.countNumberByLocationId(inventoryLocationEntity.getId());
                    inventoryLocationEntity.setNumber(ObjectUtil.isNotNull(number) ? number : 0);
                });
            }
        }
        Map<Integer, List<InventoryLocationEntity>> o = inventoryLocationEntities.stream().collect(Collectors.groupingBy(InventoryLocationEntity::getRow));
        List<InventoryILocationReq> list1 = new ArrayList<>();
        for (Map.Entry<Integer, List<InventoryLocationEntity>> entry : o.entrySet()) {
            List<InventoryLocationEntity> value = entry.getValue();
            Integer index = entry.getKey();
            //根据列排序
            value.sort(Comparator.comparingInt(InventoryLocationEntity::getColumn));
            InventoryILocationReq inventoryILocationReq = new InventoryILocationReq();
            inventoryILocationReq.setIndex(index);
            inventoryILocationReq.setChild(value);
            list1.add(inventoryILocationReq);
        }
        return list1;
    }

    public WarehouseVo<WarehouseSimpleVo> getWarehouseList(QueryWarehouseReq queryWarehouseReq) {
        List<String> goodsAreaNames = buildGoodsAreaNames(queryWarehouseReq);
        PageHelper.startPage(queryWarehouseReq.getPageNum(), queryWarehouseReq.getPageSize());
        List<WarehouseSimpleVo> wareHouseEntityList = inventoryLocationRespository.getWarehouseList(queryWarehouseReq);
        wareHouseEntityList.forEach(warehouseSimpleVo -> {
            warehouseSimpleVo.setParamMap(JSONObject.parseObject(warehouseSimpleVo.getParam()));
            warehouseSimpleVo.setParam("");
            Integer totalLocation = inventoryLocationRespository.countLocationNum(warehouseSimpleVo.getId());
            Integer freeCount = inventoryLocationRespository.countByStatus(warehouseSimpleVo.getId(), 2);
            Integer fullCount = inventoryLocationRespository.countByStatus(warehouseSimpleVo.getId(), 1);
            if (Objects.equals(totalLocation, freeCount)) {
                warehouseSimpleVo.setStatus("2");
            } else if (Objects.equals(totalLocation, fullCount)) {
                warehouseSimpleVo.setStatus("1");
            } else {
                warehouseSimpleVo.setStatus("0");
            }
        });
        PageInfo<WarehouseSimpleVo> pageInfo = new PageInfo<>(wareHouseEntityList);
//        if(CollectionUtil.isNotEmpty(pageInfo.getList())){
//            pageInfo.getList().forEach(warehouseSimpleVo -> {
//                try {
//                    //deviceClient = toolScheduleService.ConnectDevice(warehouseSimpleVo.getSnCode());
//                    DeviceClient deviceClient =
//                            new DeviceClient(warehouseSimpleVo.getSnCode(), "tcp://192.168.32.107:1883", null, null, null);
//                    deviceClient.connect();
//                    String id = deviceClient.getIdOf("/NC_LINK_ROOT/MACHNE/STATUS");
//                    List<Object> result = deviceClient.easyQuery(2000, new QueryRequestItem.Builder()
//                            .id(id).build());
//                    Object statusObject = deviceClient.easyQuery(3000,
//                            new QueryRequestItem.Builder().id(id).operation(Operation.GET_VALUE).build());
//                    warehouseSimpleVo.setMachineToolStatus(CommonUtil.getProgramString(statusObject));
//                } catch (Exception e) {
//                    log.error(e.getMessage());
//                }
//            });
//        }
        return new WarehouseVo<>(pageInfo.getList(), pageInfo.getTotal(), goodsAreaNames);
    }

    private List<String> buildGoodsAreaNames(QueryWarehouseReq queryWareHouseReq) {
        //货区名列表
        List<String> goodsAreaNames = inventoryLocationRespository.getGoodsAreaNames(queryWareHouseReq.getType());
        if ("".equals(queryWareHouseReq.getGoodsAreaName())) {
            if (!CollectionUtils.isEmpty(goodsAreaNames)) {
                //货区名为空且货区名列表不为空
                queryWareHouseReq.setGoodsAreaName(goodsAreaNames.get(0));
            }
        }
        return goodsAreaNames;
    }

    public List<InventoryLocationEntity> getLocationList(Integer warehouseId) {
        List<InventoryLocationEntity> locationList = inventoryLocationRespository.getLocationList(warehouseId);
        String warehouseType = warehouseRespository.getWarehouseType(warehouseId);
        locationList.forEach(inventoryLocationEntity -> {
            inventoryLocationEntity.setParamMap(JSONObject.parseObject(inventoryLocationEntity.getParam()));
            inventoryLocationEntity.setParam("");
            //智能柜设置库位数量
            if (warehouseType.equals("A002")) {
                inventoryLocationEntity.getParamMap().put("number", getInventory(inventoryLocationEntity.getId(), warehouseType));
            }
        });
        return locationList;
    }

    private Integer getInventory(Integer id, String type) {
        return inventoryLocationRespository.getInventory(id, type);
    }

    public List<InventoryLocationVo> getLocationChildList(Integer inventoryLocationId, String warehouseType) {
        List<InventoryLocationVo> locationEntities = new ArrayList<>();
        if (!"".equals(warehouseType) && toolWarehouseTypeList.contains(warehouseType)) {
            //刀具零件
            locationEntities = inventoryLocationRespository.getLocationToolChildList(inventoryLocationId);
        } else if (!"".equals(warehouseType) && assemblyToolWarehouseTypeList.contains(warehouseType)) {
            //总成刀具
            locationEntities = inventoryLocationRespository.getLocationAssemblyToolChildList(inventoryLocationId);
        }
        return locationEntities;
    }

    public PageResult<LocationToolVo> getLocationToolList(LocationToolReq locationToolReq) {
        List<LocationToolVo> toolVos = new ArrayList<>();
        List<LocationToolVo> pageList = new ArrayList<>();
        String warehouseType = locationToolReq.getWarehouseType();
        Integer inventoryLocationId = locationToolReq.getInventoryLocationId();
        //PageHelper.startPage(locationToolReq.getPageNum(), locationToolReq.getPageSize());
        //刀具零件
        toolVos = inventoryLocationRespository.getLocationToolList(inventoryLocationId, locationToolReq.getSearchContent());
        //总成刀具
        List<LocationToolVo> assemblyToolVos = inventoryLocationRespository.getLocationAssemblyToolList(inventoryLocationId, locationToolReq.getSearchContent());
        if (!CollectionUtils.isEmpty(assemblyToolVos)) {
            toolVos.addAll(assemblyToolVos);
        }
        //校验查询是否有结果
        if (!CollectionUtils.isEmpty(toolVos)) {
            toolVos.forEach(locationToolVo -> {
                InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(inventoryLocationId);
                if (ObjectUtil.isNotNull(inventoryLocationEntity)) {
                    String safetyInventoryConfigureParam = inventoryLocationEntity.getSafetyInventoryConfigureParam();
                    if (StringUtil.isNotEmpty(safetyInventoryConfigureParam) && !safetyInventoryConfigureParam.equals("[]")) {
                        List<SingleWarehouseSafetyInventoryParam> singleWarehouseSafetyInventoryParams = JSONArray.parseArray(safetyInventoryConfigureParam, SingleWarehouseSafetyInventoryParam.class);
                        if (CollectionUtil.isNotEmpty(singleWarehouseSafetyInventoryParams)) {
                            singleWarehouseSafetyInventoryParams.forEach(singleWarehouseSafetyInventoryParam -> {
                                //partno对接安全库存
                                if (StringUtil.isNotEmpty(locationToolVo.getPartno()) && singleWarehouseSafetyInventoryParam.getPartno().equals(locationToolVo.getPartno())) {
                                    locationToolVo.setSafetyInventory(singleWarehouseSafetyInventoryParam.getSafetyInventory());
                                }
                                //toolNo对接安全库存
                                if (StringUtil.isNotEmpty(locationToolVo.getToolNo()) && singleWarehouseSafetyInventoryParam.getToolNo().equals(locationToolVo.getToolNo())) {
                                    locationToolVo.setSafetyInventory(singleWarehouseSafetyInventoryParam.getSafetyInventory());
                                }
                            });
                        }
                    }
                }
                //查询本月出入库记录
                List<InboundAndOutboundVo> resultList = inventoryLocationRespository.queryInboundAndOutbound(locationToolVo.getId(), locationToolReq.getSearchContent());
                resultList.forEach(inboundAndOutboundVo -> {
                    if (inboundAndOutboundVo.getType().equals(CommonConstant.INBOUND_CONST)) {
                        //设置入库数量
                        locationToolVo.setInbound(inboundAndOutboundVo.getNumber());
                    } else {
                        //设置出库数量
                        locationToolVo.setOutbound(inboundAndOutboundVo.getNumber());
                    }
                });
            });
        }
        if (CollectionUtil.isNotEmpty(toolVos)) {
            pageList = CommonUtil.pageList(toolVos, locationToolReq.getPageNum(), locationToolReq.getPageSize());
        }
        return new PageResult<>(pageList, (long) toolVos.size());
    }

    public Map<String, Object> getLocationToolDetail(LocationToolDetailReq locationToolDetailReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(locationToolDetailReq.getId())) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.IDNR_NO_EXIT.getCode(), ToolLifeCycleEx.IDNR_NO_EXIT.getMsg());
        }
        ToolForkInfoEntity toolForkInfoEntity = toolForkRespository.selectById(locationToolDetailReq.getId());
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("toolForkInfo", toolForkInfoEntity);
        //PageHelper.startPage(locationToolDetailReq.getPageNum(), locationToolDetailReq.getPageSize());
        //PageInfo<ToolPartVo> pageInfo = new PageInfo<>();
        List<ToolPartVo> locationToolsDetail = toolPartRespository.getLocationToolsDetail(locationToolDetailReq);
        List<ToolPartVo> pageList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(locationToolsDetail)) {
            locationToolsDetail.forEach(toolPartVo -> {
                locationToolDetailReq.setUniqueId(toolPartVo.getUniqueId());
                ToolPartVo oneResult = toolPartRespository.getLocationToolDetail(locationToolDetailReq);
                if (ObjectUtil.isNotNull(oneResult)) {
                    toolPartVo.setInboundTime(oneResult.getInboundTime());
                }
            });
            if (ObjectUtil.isNotNull(locationToolDetailReq.getBeginTime())) {
                //根据时间过滤
                locationToolsDetail = locationToolsDetail.stream().filter(toolPartVo -> ObjectUtil.isNotNull(toolPartVo.getInboundTime())).collect(Collectors.toList());
                locationToolsDetail = locationToolsDetail.stream().filter(toolPartVo -> toolPartVo.getInboundTime().after(locationToolDetailReq.getBeginTime()) && locationToolDetailReq.getEndTime().after(toolPartVo.getInboundTime())).collect(Collectors.toList());
            }
        }
        if (CollectionUtil.isNotEmpty(locationToolsDetail)) {
            //手动分页
            pageList = CommonUtil.pageList(locationToolsDetail, locationToolDetailReq.getPageNum(), locationToolDetailReq.getPageSize());
            if (CollectionUtil.isNotEmpty(pageList)) {
                pageList.forEach(toolPartVo -> {
                    if (StringUtil.isNotEmpty(toolPartVo.getImage())) {
                        toolPartVo.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolPartVo.getImage());
                    }
                });
            }
        }
        retMap.put("list", pageList);
        retMap.put("total", locationToolsDetail.size());
        return retMap;
    }

    private void buildRetMap(ToolForkInfoEntity toolForkInfoEntity, Map<String, Object> retMap) {
        retMap.put("image", toolForkInfoEntity.getImage());
        retMap.put("idnr", toolForkInfoEntity.getIdnr());
        retMap.put("dc", toolForkInfoEntity.getDc());
        retMap.put("partno", toolForkInfoEntity.getPartno());
        retMap.put("hand", toolForkInfoEntity.getHand());
        retMap.put("oal", toolForkInfoEntity.getOal());
        retMap.put("description", toolForkInfoEntity.getDescription());
    }

    public PageResult<LocationUsageVo> getLocationUsageLog(LocationUsageReq locationUsageReq) {
        PageHelper.startPage(locationUsageReq.getPageNum(), locationUsageReq.getPageSize());
        List<LocationUsageVo> voList = inventoryLocationRespository.getLocationUsageLog(locationUsageReq);
        if (!CollectionUtils.isEmpty(voList)) {
            voList.forEach(locationUsageVo -> {
                locationUsageVo.setParamMap(JSONObject.parseObject(locationUsageVo.getParams()));
                locationUsageVo.setParams("");
            });
        }
        PageInfo<LocationUsageVo> pageInfo = new PageInfo<>(voList);
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object getLocationAssemblyToolUsageLog(LocationAssemblyToolUsageReq locationAssemblyToolUsageReq) {
        PageHelper.startPage(locationAssemblyToolUsageReq.getPageNum(), locationAssemblyToolUsageReq.getPageSize());
        List<LocationUsageVo> voList = inventoryLocationRespository.getLocationAssemblyToolUsageLog(locationAssemblyToolUsageReq);
        PageInfo<LocationUsageVo> pageInfo = new PageInfo<>(voList);
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object getToolAllocationStatus(ToolAllocationReq toolAllocationReq) {
        PageHelper.startPage(toolAllocationReq.getPageNum(), toolAllocationReq.getPageSize());
        List<AssemblyToolPartVo> voList = inventoryLocationRespository.getToolAllocationStatus(toolAllocationReq);
        PageInfo<AssemblyToolPartVo> pageInfo = new PageInfo<>(voList);
        return new PageResult<>(voList, pageInfo.getTotal());
    }

    private AssemblyToolPartVo getInboundTime(AssemblyToolPartVo assemblyToolPartVo) {
        assemblyToolPartVo.setInboundTime(toolPartRespository.getInboundTime(assemblyToolPartVo.getId()));
        return assemblyToolPartVo;
    }

    public Boolean editSafetyInventoryConfigure(WarehouseSafetyInventoryParamReq warehouseSafetyInventoryParamReq) {
        List<SingleWarehouseSafetyInventoryParam> updateList = warehouseSafetyInventoryParamReq.getSafetyInventoryParams();
        //配置仓库安全库存
        WarehouseEntity warehouseEntity = warehouseRespository.getByIdOrName(warehouseSafetyInventoryParamReq.getId(), "");
        String safetyInventoryConfigureParam = warehouseEntity.getSafetyInventoryConfigureParam();
        List<SingleWarehouseSafetyInventoryParam> originList = new ArrayList<>();
        if (StringUtil.isNotEmpty(safetyInventoryConfigureParam)) {
            originList = JSONArray.parseArray(warehouseEntity.getSafetyInventoryConfigureParam(), SingleWarehouseSafetyInventoryParam.class);
        }
        SafetyInventoryLogic safetyInventoryLogic = new SafetyInventoryLogic(originList, updateList);
        safetyInventoryLogic.buildSafetyInventoryDo();
        SafetyInventoryDo safetyInventoryDo = safetyInventoryLogic.getSafetyInventoryDo();
        List<SingleWarehouseSafetyInventoryParam> persistance = persistance(safetyInventoryDo, originList);
        warehouseEntity.setSafetyInventoryConfigureParam(JSONObject.toJSONString(persistance));
        warehouseMapper.updateById(warehouseEntity);
        return Boolean.TRUE;
    }

    private List<SingleWarehouseSafetyInventoryParam> persistance(SafetyInventoryDo safetyInventoryDo, List<SingleWarehouseSafetyInventoryParam> originList) {
        //删除
        if (CollectionUtil.isNotEmpty(safetyInventoryDo.getDeleteElement())) {
            List<SingleWarehouseSafetyInventoryParam> deleteElement = safetyInventoryDo.getDeleteElement();
            List<String> existToolNo = deleteElement.stream().map(SingleWarehouseSafetyInventoryParam::getToolNo).collect(Collectors.toList());
            List<String> existPartno = deleteElement.stream().map(SingleWarehouseSafetyInventoryParam::getPartno).collect(Collectors.toList());
            //originList = originList.stream().filter(singleWarehouseSafetyInventoryParam -> !existToolNo.contains(singleWarehouseSafetyInventoryParam.getToolNo())||!existPartno.contains(singleWarehouseSafetyInventoryParam.getPartno())).collect(Collectors.toList());
            Iterator<SingleWarehouseSafetyInventoryParam> iterator = originList.iterator();
            while (iterator.hasNext()) {
                SingleWarehouseSafetyInventoryParam next = iterator.next();
                if (StringUtil.isNotEmpty(next.getToolNo()) && existToolNo.contains(next.getToolNo()) || StringUtil.isNotEmpty(next.getPartno()) && existPartno.contains(next.getPartno())) {
                    iterator.remove();
                }
            }
        }
        // 新增
        if (CollectionUtil.isNotEmpty(safetyInventoryDo.getCreateElement())) {
            originList.addAll(safetyInventoryDo.getCreateElement());
        }
        // 修改
        List<SingleWarehouseSafetyInventoryParam> updateElement = safetyInventoryDo.getUpdateElement();
        if (CollectionUtil.isNotEmpty(updateElement)) {
            List<String> existToolNo = updateElement.stream().map(SingleWarehouseSafetyInventoryParam::getToolNo).collect(Collectors.toList());
            List<String> existPartno = updateElement.stream().map(SingleWarehouseSafetyInventoryParam::getPartno).collect(Collectors.toList());
            //originList = originList.stream().filter(singleWarehouseSafetyInventoryParam -> !existToolNo.contains(singleWarehouseSafetyInventoryParam.getToolNo())||existPartno.contains(singleWarehouseSafetyInventoryParam.getPartno())).collect(Collectors.toList());
            Iterator<SingleWarehouseSafetyInventoryParam> iterator = originList.iterator();
            while (iterator.hasNext()) {
                SingleWarehouseSafetyInventoryParam next = iterator.next();
                if (StringUtil.isNotEmpty(next.getToolNo()) && existToolNo.contains(next.getToolNo()) || StringUtil.isNotEmpty(next.getPartno()) && existPartno.contains(next.getPartno())) {
                    iterator.remove();
                }
            }
            originList.addAll(updateElement);
        }
        return originList.stream().filter(singleWarehouseSafetyInventoryParam -> StringUtil.isNotEmpty(singleWarehouseSafetyInventoryParam.getPartno()) || StringUtil.isNotEmpty(singleWarehouseSafetyInventoryParam.getToolNo())).collect(Collectors.toList());
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }


    public Boolean addOrEditLocation(AddOrEditLocationReq addOrEditLocationReq) throws ToolLifeCycleException {
        //校验行列数l
        Map<String, String> rowAndColumn = inventoryLocationRespository.qryRowAndColumn(addOrEditLocationReq.getWarehouseId());
        if (addOrEditLocationReq.getRow() > Integer.parseInt(rowAndColumn.get("row")) || addOrEditLocationReq.getColumn() > Integer.parseInt(rowAndColumn.get("column"))) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.LOCATION_ROW_COLUMN_OVERPASS.getCode(), ToolLifeCycleEx.LOCATION_ROW_COLUMN_OVERPASS.getMsg());
        }
        InventoryLocationEntity inventoryLocationEntity = new InventoryLocationEntity();
        BeanUtils.copyProperties(addOrEditLocationReq, inventoryLocationEntity);
        inventoryLocationEntity.setLastUpdateTime(new Date());
        inventoryLocationEntity.setWarehouseName(warehouseRespository.getNameByWarehouseId(addOrEditLocationReq.getWarehouseId()));
        if (ObjectUtil.isNull(addOrEditLocationReq.getId())) {
            //新增
            //校验库位编号唯一性
//            List<String> locationNumList = inventoryLocationRespository.selectLocationNumList(addOrEditLocationReq.getId());
//            if (locationNumList.contains(addOrEditLocationReq.getLocationNum())) {
//                throw new ToolLifeCycleException(ToolLifeCycleEx.LOCATION_NUM_EXIST.getCode(), ToolLifeCycleEx.LOCATION_NUM_EXIST.getMsg());
//            }
            if (ObjectUtil.isNull(inventoryLocationEntity.getUseCapacity())) {
                inventoryLocationEntity.setUseCapacity(0);
            }
            inventoryLocationRespository.addInventoryLocation(inventoryLocationEntity);
        }
        //修改
        inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
        return Boolean.TRUE;
    }

    @Transactional
    public synchronized Boolean inboundLocationToolReload(InBoundOrOutBoundReloadReq inBoundOrOutBoundReloadReq) throws ToolLifeCycleException {
        Integer number = inBoundOrOutBoundReloadReq.getNumber();
        if (number <= 0) {
            return Boolean.FALSE;
        }
        if (ObjectUtil.isNull(inBoundOrOutBoundReloadReq.getInventoryLocationId())) {
            List<Map<String, Integer>> locationIdAndNumber = findLocationIdAndNumber(inBoundOrOutBoundReloadReq.getWarehouseId(), inBoundOrOutBoundReloadReq.getNumber(), inBoundOrOutBoundReloadReq.getPartno());
            if (CollectionUtil.isNotEmpty(locationIdAndNumber)) {
                for (int i = 0; i < locationIdAndNumber.size(); i++) {
                    Map<String, Integer> stringIntegerMap = locationIdAndNumber.get(i);
                    inBoundOrOutBoundReloadReq.setInventoryLocationId(stringIntegerMap.get("inventoryLocationId"));
                    inBoundOrOutBoundReloadReq.setNumber(stringIntegerMap.get("number"));
                    inboundLocationTool(inBoundOrOutBoundReloadReq);
                }
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 根据类型和可用库位
     *
     * @param warehouseId
     * @param number
     * @param partno
     * @return
     */
    public List<Map<String, Integer>> findLocationIdAndNumber(Integer warehouseId, Integer number, String partno) {
        List<Map<String, Integer>> paramList = new ArrayList<>();
        //入库库位为空，则印射库位信息
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.qryLocationReload(warehouseId, partno);
        //过滤掉状态为禁用和满了的
        if (CollectionUtil.isNotEmpty(inventoryLocationEntities)) {
            inventoryLocationEntities = inventoryLocationEntities.stream().filter(inventoryLocationEntity -> inventoryLocationEntity.getStatus() != 2 || inventoryLocationEntity.getStatus() != 3).sorted(Comparator.comparing(InventoryLocationEntity::getUseCapacity).reversed()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(inventoryLocationEntities)) {
                for (int i = 0; i < inventoryLocationEntities.size(); i++) {
                    //分配入库数量
                    if (number <= 0) {
                        break;
                    }
                    Map<String, Integer> retMap = new HashMap<>();
                    InventoryLocationEntity inventoryLocationEntity = inventoryLocationEntities.get(i);
                    Integer allotNumber = inventoryLocationEntity.getCapacity() - inventoryLocationEntity.getUseCapacity();
                    retMap.put("inventoryLocationId", inventoryLocationEntity.getId());
                    retMap.put("number", allotNumber);
                    paramList.add(retMap);
                    number = number - allotNumber;
                }
            }
        }
        //TO DO（多余的分配给全类型库位）
        if (number >= 0) {
            InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.selectByAllTypeLocation(warehouseId, "allType");
            Map<String, Integer> retMap = new HashMap<>();
            retMap.put("inventoryLocationId", inventoryLocationEntity.getId());
            retMap.put("number", number);
            paramList.add(retMap);
        }
        return paramList;
    }


    @Transactional
    public synchronized Boolean inboundLocationTool(InBoundOrOutBoundReq inBoundOrOutBoundReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(inBoundOrOutBoundReq.getNumber()) || inBoundOrOutBoundReq.getNumber() == 0) {
            return Boolean.FALSE;
        }
        //校验类型信息是否存在
        ToolForkInfoEntity toolForkInfoEntity = checkToolForkTypeExist(inBoundOrOutBoundReq);
        //校验库位容量
        checkCapacity(inBoundOrOutBoundReq.getInventoryLocationId(), inBoundOrOutBoundReq.getNumber());
        //判断新增还是修改
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setId(toolForkInfoEntity.getId());
        queryVo.setInventoryLocationId(inBoundOrOutBoundReq.getInventoryLocationId());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(inBoundOrOutBoundReq.getNumber(), toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(inBoundOrOutBoundReq.getInventoryLocationId());
            toolInventoryLocationEntity.setToolId(toolForkInfoEntity.getId());
            toolInventoryLocationEntity.setPhysicalInventory(inBoundOrOutBoundReq.getNumber());
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
            toolForkInfoEntity.setPartType(toolForkInfoEntity.getIdnr());
            toolForkInfoEntity.setToolNo(inBoundOrOutBoundReq.getToolNo());
            toolForkInfoMapper.updateById(toolForkInfoEntity);
        }
        updateLocationUseCapacity(inBoundOrOutBoundReq.getInventoryLocationId(), inBoundOrOutBoundReq.getNumber());
        //给入库刀具分配唯一编码
        List<Integer> toolPartIdList = toolPartService.buildToolUniqueId(toolInventoryLocationEntity, inBoundOrOutBoundReq.getNumber(), inBoundOrOutBoundReq.getPartno(), inBoundOrOutBoundReq.getLife());
        //生成入库记录
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inBoundOrOutBoundReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, inBoundOrOutBoundReq.getOperator(), inBoundOrOutBoundReq.getBz(), "", "", new Date());
        return Boolean.TRUE;
    }

    @Transactional
    public synchronized Boolean inboundLocationTool(InBoundOrOutBoundTimeReq InBoundOrOutBoundtimeReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(InBoundOrOutBoundtimeReq.getNumber()) || InBoundOrOutBoundtimeReq.getNumber() == 0) {
            return Boolean.FALSE;
        }
        //校验类型信息是否存在
        ToolForkInfoEntity toolForkInfoEntity = checkToolForkTypeExist(InBoundOrOutBoundtimeReq);
        //校验库位容量
        checkCapacity(InBoundOrOutBoundtimeReq.getInventoryLocationId(), InBoundOrOutBoundtimeReq.getNumber());
        //判断新增还是修改
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setId(toolForkInfoEntity.getId());
        queryVo.setInventoryLocationId(InBoundOrOutBoundtimeReq.getInventoryLocationId());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(InBoundOrOutBoundtimeReq.getNumber(), toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(InBoundOrOutBoundtimeReq.getInventoryLocationId());
            toolInventoryLocationEntity.setToolId(toolForkInfoEntity.getId());
            toolInventoryLocationEntity.setPhysicalInventory(InBoundOrOutBoundtimeReq.getNumber());
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
            toolForkInfoEntity.setPartType(toolForkInfoEntity.getIdnr());
            toolForkInfoEntity.setToolNo(InBoundOrOutBoundtimeReq.getToolNo());
            toolForkInfoMapper.updateById(toolForkInfoEntity);
        }
        updateLocationUseCapacity(InBoundOrOutBoundtimeReq.getInventoryLocationId(), InBoundOrOutBoundtimeReq.getNumber());
        //给入库刀具分配唯一编码
        List<Integer> toolPartIdList = toolPartService.buildToolUniqueId(toolInventoryLocationEntity, InBoundOrOutBoundtimeReq.getNumber(), InBoundOrOutBoundtimeReq.getLife(), InBoundOrOutBoundtimeReq.getPartno());
        //生成入库记录
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, InBoundOrOutBoundtimeReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, InBoundOrOutBoundtimeReq.getOperator(), InBoundOrOutBoundtimeReq.getBz(), "", "", InBoundOrOutBoundtimeReq.getCreateTime());
        return Boolean.TRUE;
    }

    private void updateLocationUseCapacity(Integer inventoryLocationId, Integer number) {
        //库位使用容量修改
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(inventoryLocationId);
        if (inventoryLocationEntity != null) {
            inventoryLocationEntity.setUseCapacity(inventoryLocationEntity.getUseCapacity() + number);
            //设置库位容量状态位
            if (number != 0 && inventoryLocationEntity.getUseCapacity() == inventoryLocationEntity.getCapacity()) {
                inventoryLocationEntity.setStatus(InventoryStatusEnum.FULL.getCode());
            } else {
                inventoryLocationEntity.setStatus(InventoryStatusEnum.FREE.getCode());
            }
            inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
            //修改货架状态
            updateWarehouseStatus(inventoryLocationEntity);
        }

    }

    private void updateWarehouseStatus(InventoryLocationEntity inventoryLocationEntity) {
        Integer i = 0;
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectListByWarehouseId(inventoryLocationEntity.getWarehouseId(), inventoryLocationEntity.getId());
        if (inventoryLocationEntity.getStatus() == 3 && CollectionUtil.isEmpty(inventoryLocationEntities)) {
            i = InventoryStatusEnum.BAN.getCode();
        } else {
            inventoryLocationEntities.add(inventoryLocationEntity);
            int sum = inventoryLocationEntities.stream().mapToInt(InventoryLocationEntity::getStatus).sum();
            //判断仓库状态
            int size = inventoryLocationEntities.size();
            if (0 == sum) {
                //设置状态为空余
                i = InventoryStatusEnum.FREE.getCode();
            } else if (sum == size) {
                //设置状态为满仓
                i = InventoryStatusEnum.FULL.getCode();
            } else {
                //设置状态为空仓
                i = InventoryStatusEnum.EMPTY.getCode();
            }
        }
        warehouseRespository.updateStatus(inventoryLocationEntity.getWarehouseId(), i);
    }

    @Transactional
    public synchronized Boolean inboundLocationAssemblyTool(InBoundOrOutBoundAssemblyReq inBoundOrOutBoundAssemblyReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(inBoundOrOutBoundAssemblyReq.getNumber()) || inBoundOrOutBoundAssemblyReq.getNumber() == 0) {
            return Boolean.FALSE;
        }
        //校验库位容量
        //checkCapacity(inBoundOrOutBoundAssemblyReq.getInventoryLocationId(), inBoundOrOutBoundAssemblyReq.getNumber());
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = buildAssemblyInventoryEntity(inBoundOrOutBoundAssemblyReq);
        ToolInventoryLocationEntity toolInventoryLocationEntity = insertToolInventoryLocation(inBoundOrOutBoundAssemblyReq.getNumber(), inBoundOrOutBoundAssemblyReq.getInventoryLocationId(), assemblyToolInventoryEntity);
//        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
//        queryVo.setAssemblyToolId(assemblyToolInventoryEntity.getId());
//        queryVo.setInventoryLocationId(inBoundOrOutBoundAssemblyReq.getInventoryLocationId());
//        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
//        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
//            //修改
//            updatePhysicalInventory(inBoundOrOutBoundAssemblyReq.getNumber(), toolInventoryLocationEntity);
//        } else {
//            //新增
//            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
//            toolInventoryLocationEntity.setInventoryLocationId(inBoundOrOutBoundAssemblyReq.getInventoryLocationId());
//            toolInventoryLocationEntity.setAssemblyToolInventoryId(assemblyToolInventoryEntity.getId());
//            toolInventoryLocationEntity.setPhysicalInventory(inBoundOrOutBoundAssemblyReq.getNumber());
//            toolInventoryLocationEntity.setLastUpdateTime(new Date());
//            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
//        }
//        //库位使用容量修改
//        updateLocationUseCapacity(inBoundOrOutBoundAssemblyReq.getInventoryLocationId(), inBoundOrOutBoundAssemblyReq.getNumber());
        //生成唯一编号
        List<ToolPartEntity> toolPartList = toolPartService.buildAssemblyUniqueId(toolInventoryLocationEntity, inBoundOrOutBoundAssemblyReq, assemblyToolInventoryEntity);
        List<Integer> toolPartIdList = toolPartList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        String toolPartParams = buildToolPartParams(toolPartList.get(0));
        //生成入库记录
        entryExitRecordService.createEntryRecordReload(toolInventoryLocationEntity, inBoundOrOutBoundAssemblyReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, inBoundOrOutBoundAssemblyReq.getOperator(), inBoundOrOutBoundAssemblyReq.getBz(), "", "", new Date() , toolPartParams);
        return Boolean.TRUE;
    }

    @NotNull
    private AssemblyToolInventoryEntity buildAssemblyInventoryEntity(InBoundOrOutBoundAssemblyReq inBoundOrOutBoundAssemblyReq) {
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = null;
        assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(inBoundOrOutBoundAssemblyReq.getToolNo());
        if (ObjectUtil.isNull(assemblyToolInventoryEntity)) {
            assemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
            BeanUtils.copyProperties(inBoundOrOutBoundAssemblyReq, assemblyToolInventoryEntity);
            assemblyToolInventoryEntity.setName("总成" + System.currentTimeMillis());
            assemblyToolInventoryMapper.insert(assemblyToolInventoryEntity);
        }
        return assemblyToolInventoryEntity;
    }

    private AssemblyToolInventoryEntity queryOneAssemblyToolInventoryEntity(String toolNo) {
        QueryWrapper<AssemblyToolInventoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tool_no", toolNo);
        return assemblyToolInventoryMapper.selectOne(wrapper);
    }

    private void updatePhysicalInventory(Integer number, ToolInventoryLocationEntity toolInventoryLocationEntity) throws ToolLifeCycleException {
        //校验实际库存与操作数量
//        if(number > toolInventoryLocationEntity.getPhysicalInventory()){
//            throw new ToolLifeCycleException(ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getCode() , ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getMsg());
//        }
        if (ObjectUtil.isNull(toolInventoryLocationEntity.getPhysicalInventory())) {
            toolInventoryLocationEntity.setPhysicalInventory(number);
        } else {
            toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() + number);
        }
        toolInventoryLocationEntity.setLastUpdateTime(new Date());
        toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
    }

    private AssemblyToolInventoryEntity checkAssemblyToolTypeExist(String toolNo) throws ToolLifeCycleException {
        QueryWrapper<AssemblyToolInventoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tool_no", toolNo);
        AssemblyToolInventoryEntity assemblyToolEntity = assemblyToolInventoryMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(assemblyToolEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.ASSEMBLY_TOOL_TYPE_NO_EXIT.getCode(), ToolLifeCycleEx.ASSEMBLY_TOOL_TYPE_NO_EXIT.getMsg());
        }
        return assemblyToolEntity;
    }

    private void checkCapacity(Integer inventoryLocationId, Integer number) throws ToolLifeCycleException {
        Map<String, Integer> capacityMap = inventoryLocationRespository.queryCapacity(inventoryLocationId);
        if (CollectionUtil.isNotEmpty(capacityMap)) {
            if (capacityMap.getOrDefault("capacity", 0) < capacityMap.getOrDefault("use_capacity", 0) + number) {
                throw new ToolLifeCycleException(ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getMsg());
            }
        }

    }


    private ToolForkInfoEntity checkToolForkTypeExist(InBoundOrOutBoundReq inBoundOrOutBoundReq) throws ToolLifeCycleException {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("partno", inBoundOrOutBoundReq.getPartno());
        //wrapper.eq("idnr", inBoundOrOutBoundReq.getIdnr());
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(toolForkInfoEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_FORK_TYPE_NO_EXIT.getCode(), ToolLifeCycleEx.TOOL_FORK_TYPE_NO_EXIT.getMsg());
        }
        return toolForkInfoEntity;
    }

    private ToolForkInfoEntity checkToolForkTypeExistByType(String partno) throws ToolLifeCycleException {
        QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("partno", partno);
        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(toolForkInfoEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_FORK_TYPE_NO_EXIT.getCode(), ToolLifeCycleEx.TOOL_FORK_TYPE_NO_EXIT.getMsg());
        }
        //TO DO 确认具体的物料类型
        return toolForkInfoEntity;
    }


    /**
     * 删除货架
     *
     * @param id
     */
    public void deleteShelves(Integer id) throws ShelvesException {
        Integer rows = inventoryLocationRespository.deleteShelvesById(id);
        if (rows != 1) {
            throw new ShelvesException(ShelvesEx.SHELVES_DELETE_ERROR.getCode(), ShelvesEx.SHELVES_DELETE_ERROR.getMsg());
        } else {
            inventoryLocationRespository.deleteShelveWarehouse(id);
        }
    }

    /**
     * 新增或者修改货架
     */
    public void addShelves(AddShelvesReq addShelvesReq) throws ShelvesException {

        if (addShelvesReq.getId() == null) {
            WarehouseEntity addShelvesReq1 = initialization(addShelvesReq);
            HashMap<String, String> map = new HashMap<>();

            map.put("row", addShelvesReq.getRow());
            map.put("column", addShelvesReq.getColumn());
            addShelvesReq1.setParam(JSONObject.toJSONString(map));
            Integer rows = inventoryLocationRespository.insertShelves(addShelvesReq1);
            if (rows != 1) {
                throw new ShelvesException(ShelvesEx.SHELVES_INSERT_ERROR.getCode(), ShelvesEx.SHELVES_INSERT_ERROR.getMsg());
            }

        } else {
            WarehouseEntity addShelvesReq1 = initialization(addShelvesReq);
            addShelvesReq1.setId(addShelvesReq.getId());
            HashMap<String, String> map = new HashMap<>();

            map.put("row", addShelvesReq.getRow());
            map.put("column", addShelvesReq.getColumn());
            addShelvesReq1.setParam(JSONObject.toJSONString(map));

            Integer rows = inventoryLocationRespository.updateShelves(addShelvesReq1);
            if (rows != 1) {
                throw new ShelvesException(ShelvesEx.SHELVES_UPDATE_ERROR.getCode(), ShelvesEx.SHELVES_UPDATE_ERROR.getMsg());
            }

        }

    }

    /**
     * 对货架信息进行赋值
     *
     * @param addShelvesReq
     * @return
     */
    public WarehouseEntity initialization(AddShelvesReq addShelvesReq) {
        WarehouseEntity addShelvesReq1 = new WarehouseEntity();
        addShelvesReq1.setRow(addShelvesReq.getRow());
        addShelvesReq1.setColumn(addShelvesReq.getColumn());
        addShelvesReq1.setGoodsAreaName(addShelvesReq.getGoodsAreaName());
        addShelvesReq1.setName(addShelvesReq.getName());
        addShelvesReq1.setStatus(addShelvesReq.getStatus());
        addShelvesReq1.setType(addShelvesReq.getType());
        return addShelvesReq1;
    }

    @Transactional
    public synchronized List<ToolPartEntity> outboundLocationTool(InBoundOrOutBoundReq inBoundOrOutBoundReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(inBoundOrOutBoundReq.getNumber()) || inBoundOrOutBoundReq.getNumber() == 0) {
            return new ArrayList<>();
        }
        //校验类型信息是否存在
        ToolForkInfoEntity toolForkInfoEntity = checkToolForkTypeExist(inBoundOrOutBoundReq);
        //校验操作数量
        checkOutBoundNumber(inBoundOrOutBoundReq, toolForkInfoEntity.getId());
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setInventoryLocationId(inBoundOrOutBoundReq.getInventoryLocationId());
        queryVo.setId(toolForkInfoEntity.getId());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        return outboundTool(inBoundOrOutBoundReq, toolForkInfoEntity, toolInventoryLocationEntity);
    }

    @Transactional
    public synchronized List<ToolPartEntity> outboundLocationTool(InBoundOrOutBoundTimeReq inBoundOrOutBoundReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(inBoundOrOutBoundReq.getNumber()) || inBoundOrOutBoundReq.getNumber() == 0) {
            return new ArrayList<>();
        }
        //校验类型信息是否存在
        ToolForkInfoEntity toolForkInfoEntity = checkToolForkTypeExist(inBoundOrOutBoundReq);
        //校验操作数量
        checkOutBoundNumber(inBoundOrOutBoundReq, toolForkInfoEntity.getId());
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setInventoryLocationId(inBoundOrOutBoundReq.getInventoryLocationId());
        queryVo.setId(toolForkInfoEntity.getId());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        if (ObjectUtil.isNull(toolInventoryLocationEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        return outboundTool(inBoundOrOutBoundReq, toolForkInfoEntity, toolInventoryLocationEntity);
    }

    private List<ToolPartEntity> outboundTool(InBoundOrOutBoundReq inBoundOrOutBoundReq, ToolForkInfoEntity toolForkInfoEntity, ToolInventoryLocationEntity toolInventoryLocationEntity) throws ToolLifeCycleException {
        //校验实际库存数量
        if (ObjectUtil.isNull(toolInventoryLocationEntity.getPhysicalInventory()) || toolInventoryLocationEntity.getPhysicalInventory() == 0 || inBoundOrOutBoundReq.getNumber() > toolInventoryLocationEntity.getPhysicalInventory()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getMsg());
        }
        toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() - inBoundOrOutBoundReq.getNumber());
        toolInventoryLocationEntity.setLastUpdateTime(new Date());
        toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
        //库位使用容量修改
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(inBoundOrOutBoundReq.getInventoryLocationId());
        inventoryLocationEntity.setUseCapacity(inventoryLocationEntity.getUseCapacity() - inBoundOrOutBoundReq.getNumber());
        //设置库存状态位
        if (inventoryLocationEntity.getUseCapacity() == 0) {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.EMPTY.getCode());
        } else {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.FREE.getCode());
        }
        inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
        updateWarehouseStatus(inventoryLocationEntity);
        //随机从集合中取出对应数量的元素
        List<ToolPartEntity> outboundList = toolPartService.toolOutBound(toolForkInfoEntity, toolInventoryLocationEntity.getInventoryLocationId(), inBoundOrOutBoundReq.getNumber());
        if (CollectionUtil.isEmpty(outboundList)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        List<Integer> idList = outboundList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        //往库存记录表中添加数据
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inBoundOrOutBoundReq.getNumber(), idList, CommonConstant.OUTBOUND_CONST, inBoundOrOutBoundReq.getOperator(), inBoundOrOutBoundReq.getBz(), inBoundOrOutBoundReq.getTaskId(), inBoundOrOutBoundReq.getProductionNum(), new Date());
        return outboundList;
    }

    private List<ToolPartEntity> outboundTool(InBoundOrOutBoundTimeReq inBoundOrOutBoundReq, ToolForkInfoEntity toolForkInfoEntity, ToolInventoryLocationEntity toolInventoryLocationEntity) throws ToolLifeCycleException {
        //校验实际库存数量
        if (ObjectUtil.isNull(toolInventoryLocationEntity.getPhysicalInventory()) || toolInventoryLocationEntity.getPhysicalInventory() == 0 || inBoundOrOutBoundReq.getNumber() > toolInventoryLocationEntity.getPhysicalInventory()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getMsg());
        }
        toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() - inBoundOrOutBoundReq.getNumber());
        toolInventoryLocationEntity.setLastUpdateTime(new Date());
        toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
        //库位使用容量修改
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(inBoundOrOutBoundReq.getInventoryLocationId());
        inventoryLocationEntity.setUseCapacity(inventoryLocationEntity.getUseCapacity() - inBoundOrOutBoundReq.getNumber());
        //设置库存状态位
        if (inventoryLocationEntity.getUseCapacity() - inBoundOrOutBoundReq.getNumber() == 0) {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.EMPTY.getCode());
        } else {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.FREE.getCode());
        }
        inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
        //随机从集合中取出对应数量的元素
        List<ToolPartEntity> outboundList = toolPartService.toolOutBound(toolForkInfoEntity, toolInventoryLocationEntity.getInventoryLocationId(), inBoundOrOutBoundReq.getNumber());
        List<Integer> idList = outboundList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        //往库存记录表中添加数据
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inBoundOrOutBoundReq.getNumber(), idList, CommonConstant.OUTBOUND_CONST, inBoundOrOutBoundReq.getOperator(), inBoundOrOutBoundReq.getBz(), inBoundOrOutBoundReq.getTaskId(), inBoundOrOutBoundReq.getProductionNum(), inBoundOrOutBoundReq.getCreateTime());
        return outboundList;
    }

    private void checkOutBoundNumber(InBoundOrOutBoundReq inBoundOrOutBoundReq, Integer toolId) throws ToolLifeCycleException {
        Integer physicalInventory = toolInventoryLocationRespository.getPhysicalInventory(inBoundOrOutBoundReq.getInventoryLocationId(), toolId);
        if (ObjectUtil.isNull(physicalInventory) || physicalInventory.equals(0) || physicalInventory < inBoundOrOutBoundReq.getNumber()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.INBOUND_OR_OUTBOUND_NUMBER_EXCEED.getMsg());
        }
    }

    public Object qrySafetyInventoryConfigure(Integer id, String toolNo, String partno, Integer flag) {
        List<SingleWarehouseSafetyInventoryParam> singleWarehouseSafetyInventoryParams = new ArrayList<>();
        if (flag == 0) {
            WarehouseEntity warehouseEntity = warehouseRespository.getByIdOrName(id, "");
            singleWarehouseSafetyInventoryParams = JSONArray.parseArray(warehouseEntity.getSafetyInventoryConfigureParam(), SingleWarehouseSafetyInventoryParam.class);
        } else {
            InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(id);
            singleWarehouseSafetyInventoryParams = JSONArray.parseArray(inventoryLocationEntity.getSafetyInventoryConfigureParam(), SingleWarehouseSafetyInventoryParam.class);
        }
        if (CollectionUtil.isEmpty(singleWarehouseSafetyInventoryParams)) {
            return new ArrayList<>();
        }
        if (StringUtil.isNotEmpty(toolNo)) {
            List<SingleWarehouseSafetyInventoryParam> toolNoFilterList = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> singleWarehouseSafetyInventoryParam.getToolNo().contains(toolNo)).collect(Collectors.toList());
            List<SingleWarehouseSafetyInventoryParam> toolNoUnFilterList = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> !singleWarehouseSafetyInventoryParam.getToolNo().contains(toolNo)).collect(Collectors.toList());
            toolNoFilterList.addAll(toolNoUnFilterList);
            singleWarehouseSafetyInventoryParams = toolNoFilterList;
            //singleWarehouseSafetyInventoryParams = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> toolNo.equals(singleWarehouseSafetyInventoryParam.getToolNo())).collect(Collectors.toList());
            //singleWarehouseSafetyInventoryParams = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> !toolNo.equals(singleWarehouseSafetyInventoryParam.getToolNo())).collect(Collectors.toList());
        }
        if (StringUtil.isNotEmpty(partno) && CollectionUtil.isNotEmpty(singleWarehouseSafetyInventoryParams)) {
            List<SingleWarehouseSafetyInventoryParam> partnoFilterList = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> singleWarehouseSafetyInventoryParam.getPartno().contains(partno)).collect(Collectors.toList());
            List<SingleWarehouseSafetyInventoryParam> partnoUnFilterList = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> !singleWarehouseSafetyInventoryParam.getPartno().contains(partno)).collect(Collectors.toList());
            partnoFilterList.addAll(partnoUnFilterList);
            singleWarehouseSafetyInventoryParams = partnoFilterList;
            //singleWarehouseSafetyInventoryParams = singleWarehouseSafetyInventoryParams.stream().filter(singleWarehouseSafetyInventoryParam -> partno.equals(singleWarehouseSafetyInventoryParam.getToolNo())).collect(Collectors.toList());
        }
        return singleWarehouseSafetyInventoryParams;
    }

    @Transactional
    public synchronized List<ToolPartEntity> outboundLocationAssemblyTool(OutBoundAssemblyReq outBoundAssemblyReq) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(outBoundAssemblyReq.getNumber()) || outBoundAssemblyReq.getNumber() == 0) {
            return new ArrayList<>();
        }
        Integer id = outBoundAssemblyReq.getAssemblyToolInventoryId();
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectById(id);
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setAssemblyToolId(assemblyToolInventoryEntity.getId());
        queryVo.setInventoryLocationId(outBoundAssemblyReq.getInventoryLocationId());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        outboundAssemblyToolUpdateNumber(outBoundAssemblyReq.getNumber(), outBoundAssemblyReq.getInventoryLocationId(), toolInventoryLocationEntity);
        List<ToolPartEntity> outboundList = toolPartService.outAssemblyTool(assemblyToolInventoryEntity, toolInventoryLocationEntity.getInventoryLocationId(), outBoundAssemblyReq.getNumber());
        List<Integer> idList = outboundList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        //往库存记录表中添加数据
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, outBoundAssemblyReq.getNumber(), idList, CommonConstant.OUTBOUND_CONST, outBoundAssemblyReq.getOperator(), outBoundAssemblyReq.getBz(), "", "", new Date());
        return outboundList;
    }

    private void outboundAssemblyToolUpdateNumber(Integer number, Integer locationId, ToolInventoryLocationEntity toolInventoryLocationEntity) throws ToolLifeCycleException {
        if (ObjectUtil.isNull(toolInventoryLocationEntity.getPhysicalInventory()) || toolInventoryLocationEntity.getPhysicalInventory() == 0 || number > toolInventoryLocationEntity.getPhysicalInventory()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getMsg());
        }
        toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() - number);
        toolInventoryLocationEntity.setLastUpdateTime(new Date());
        toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
        //库位使用容量修改
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(locationId);
        inventoryLocationEntity.setUseCapacity(inventoryLocationEntity.getUseCapacity() - number);
        if (inventoryLocationEntity.getUseCapacity() == 0) {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.EMPTY.getCode());
        } else {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.FREE.getCode());
        }
        inventoryLocationRespository.updateCapacityById(inventoryLocationEntity);
        updateWarehouseStatus(inventoryLocationEntity);
    }

    @Transactional
    public Object outboundUniqueAssemblyTool(OutboundUniqueAssemblyReq outboundUniqueAssemblyReq) throws ToolLifeCycleException {
        List<UniqueAssemblyToolVo> batchAssemblyTool = outboundUniqueAssemblyReq.getBatchAssemblyTool();
        if (CollectionUtil.isNotEmpty(batchAssemblyTool)) {
            for (UniqueAssemblyToolVo uniqueAssemblyToolVo : batchAssemblyTool) {
                ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOne(uniqueAssemblyToolVo.getInventoryLocationId(), uniqueAssemblyToolVo.getToolNo());
                if (ObjectUtil.isNull(toolInventoryLocationEntity)) {
                    throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());

                }
                outboundAssemblyToolUpdateNumber(1, uniqueAssemblyToolVo.getInventoryLocationId(), toolInventoryLocationEntity);
                inventoryLocationRespository.updateLocationIdById(uniqueAssemblyToolVo.getId());
                //往库存记录表中添加数据
                entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, 1, Collections.singletonList(uniqueAssemblyToolVo.getId()), CommonConstant.OUTBOUND_CONST, outboundUniqueAssemblyReq.getOperator(), outboundUniqueAssemblyReq.getBz(), "", "", new Date());
            }
        }
        return Boolean.TRUE;
    }

    public Object uploadFile(MultipartFile file, String toolNo) {
        Map<String, String> retMap = new HashMap<>();
        //上传文件
        String filename = toolNo + System.currentTimeMillis() + ".jpg";
        minioHelper.uploadFile(file, filename);
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(toolNo);
        if (ObjectUtil.isNotNull(assemblyToolInventoryEntity)) {
            assemblyToolInventoryEntity.setImage(filename);
            assemblyToolInventoryMapper.updateById(assemblyToolInventoryEntity);
        }
        retMap.put("image", filename);
        return retMap;
    }

    public Object uploadFile(MultipartFile file, String toolNo, String flag) {
        Map<String, String> retMap = new HashMap<>();
        //上传文件
        String filename = toolNo + System.currentTimeMillis() + ".jpg";
        //minioHelper.uploadFile(file, filename);
        //执行文件上传策略
        Context context = new Context();
        context.uploadByStrategy(flag, file, filename);
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(toolNo);
        if (ObjectUtil.isNotNull(assemblyToolInventoryEntity)) {
            assemblyToolInventoryEntity.setImage(filename);
            assemblyToolInventoryMapper.updateById(assemblyToolInventoryEntity);
        }
        retMap.put("image", filename);
        return retMap;
    }

    public void addOrEditSmartLocation(AddOrEditSmartLocationReq addOrEditSmartLocationReq) throws ToolLifeCycleException {
        //校验行列数
        Map<String, String> rowAndColumn = inventoryLocationRespository.qryRowAndColumn(addOrEditSmartLocationReq.getWarehouseId());
        if (addOrEditSmartLocationReq.getRow() > Integer.parseInt(rowAndColumn.get("row")) || addOrEditSmartLocationReq.getColumn() > Integer.parseInt(rowAndColumn.get("column"))) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.LOCATION_ROW_COLUMN_OVERPASS.getCode(), ToolLifeCycleEx.LOCATION_ROW_COLUMN_OVERPASS.getMsg());
        }
        InventoryLocationEntity inventoryLocationEntity = new InventoryLocationEntity();
        BeanUtils.copyProperties(addOrEditSmartLocationReq, inventoryLocationEntity);
        inventoryLocationEntity.setLastUpdateTime(new Date());
        inventoryLocationEntity.setUseCapacity(0);
        inventoryLocationEntity.setStatus(0);
        buildParams(addOrEditSmartLocationReq, inventoryLocationEntity);
        if (ObjectUtil.isNull(addOrEditSmartLocationReq.getId())) {
//            //新增 校验库位编号唯一性
//            List<String> locationNumList = inventoryLocationRespository.selectLocationNumList(addOrEditSmartLocationReq.getId());
//            if (locationNumList.contains(addOrEditSmartLocationReq.getLocationNum())) {
//                throw new ToolLifeCycleException(ToolLifeCycleEx.LOCATION_NUM_EXIST.getCode(), ToolLifeCycleEx.LOCATION_NUM_EXIST.getMsg());
//            }
            if (ObjectUtil.isNull(inventoryLocationEntity.getUseCapacity())) {
                inventoryLocationEntity.setUseCapacity(0);
            }
            inventoryLocationRespository.addInventoryLocation(inventoryLocationEntity);
        }
        //修改
        inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
    }

    private void buildParams(AddOrEditSmartLocationReq addOrEditSmartLocationReq, InventoryLocationEntity inventoryLocationEntity) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("idnr", addOrEditSmartLocationReq.getIdnr());
        paramMap.put("partno", addOrEditSmartLocationReq.getPartno());
        paramMap.put("brand", addOrEditSmartLocationReq.getBrand());
        paramMap.put("toolType", addOrEditSmartLocationReq.getToolType());
        paramMap.put("unit", addOrEditSmartLocationReq.getUnit());
        paramMap.put("number", 0);
        inventoryLocationEntity.setParam(JSONObject.toJSONString(paramMap));
    }

    public void importData(List<ToolConnectImport> importData, List<ToolConnectSimpleImport> importData1) {
        List<ToolConnectEntity> existEntities = toolConnectMapper.selectList(new QueryWrapper<>());
        if (!CollectionUtils.isEmpty(importData)) {
            List<ToolConnectEntity> toolConnectEntities = importData.stream().map(toolConnectImport -> {
                ToolConnectEntity toolConnectEntity = new ToolConnectEntity();
                BeanUtils.copyProperties(toolConnectImport, toolConnectEntity);
                return toolConnectEntity;
            }).collect(Collectors.toList());
            existEntities.addAll(toolConnectEntities);
        }
        if (!CollectionUtils.isEmpty(importData1)) {
            List<ToolConnectEntity> toolConnectEntities1 = importData1.stream().map(toolConnectSimpleImport -> {
                ToolConnectEntity toolConnectEntity = new ToolConnectEntity();
                BeanUtils.copyProperties(toolConnectSimpleImport, toolConnectEntity);
                return toolConnectEntity;
            }).collect(Collectors.toList());
            existEntities.addAll(toolConnectEntities1);
        }
        //去重
        List<ToolConnectEntity> insertEntities = existEntities.stream().distinct().collect(Collectors.toList());
        toolConnectMapper.insertBatchSomeColumn(insertEntities);
    }

    public void addSafetyCapacity(AddSafetyCapacityReq addSafetyCapacityReq) {

        //确定要加入的货区
        Integer id = inventoryLocationRespository.getIdByTypenameAndType(addSafetyCapacityReq.getTypename(), addSafetyCapacityReq.getType());

        List<SafetyCapacityDetailReq> list = addSafetyCapacityReq.getList();

        //  List<SafetyCapacityDetailReq> collect = list.stream().filter(distinctByKey(SafetyCapacityDetailReq::getToolNumber)).collect(Collectors.toList());

        List<SafetyCapacityDetailReq> collect = list.stream().distinct().collect(Collectors.toList());


        String s = JSONArray.toJSONString(collect);

        inventoryLocationRespository.updateSafetyCapcacityById(id, s);
    }

    public List<SafetyCapacityDetailReq> showSafetyCapacity(AddSafetyCapacityReq addSafetyCapacityReq) {

        Integer id = inventoryLocationRespository.getIdByTypenameAndType(addSafetyCapacityReq.getTypename(), addSafetyCapacityReq.getType());

        String s = inventoryLocationRespository.selectSafetyCapacityByid(id);

        List<SafetyCapacityDetailReq> list = JSONObject.parseArray(s, SafetyCapacityDetailReq.class);
        return list;

    }

    public Object queryAllLocation(String warehouseType, String warehouseId, String locationNum, String toolNo) {
        Map<String, Object> retMap = new HashMap<>();
        List<Map<String, Object>> warehouseList = new ArrayList<>();
        List<Map<String, Object>> locationNumList = new ArrayList<>();
        List<LocationNumVo> locationList = new ArrayList<>();
        if (StringUtil.isNotEmpty(warehouseType) && StringUtils.isBlank(warehouseId)) {
            warehouseList = warehouseRespository.selectWarehouseByType(warehouseType, toolNo);
            if (CollectionUtil.isEmpty(warehouseList)) {
                warehouseList = warehouseRespository.selectWarehouseByType(warehouseType, "");
            }
        }
        if (StringUtil.isNotEmpty(warehouseId) && StringUtils.isBlank(locationNum)) {
            Integer tranWarehouseId = Integer.valueOf(warehouseId);
            locationNumList = inventoryLocationRespository.selectLocationNumByWarehouseId(tranWarehouseId, toolNo);
            if (CollectionUtil.isEmpty(locationNumList)) {
                locationNumList = inventoryLocationRespository.selectLocationNumByWarehouseId(tranWarehouseId, "");
            }
//            locationList = inventoryLocationRespository.selectLocationByLocationNum("", tranWarehouseId);
//            if (CollectionUtil.isNotEmpty(locationList)) {
//                locationList = locationList.stream().sorted(Comparator.comparing(LocationNumVo::getRow).thenComparing(LocationNumVo::getColumn)).collect(Collectors.toList());
//            }
        }
        if (StringUtil.isNotEmpty(locationNum)) {
            Integer tranWarehouseId = Integer.valueOf(warehouseId);
            locationList = inventoryLocationRespository.selectLocationByLocationNum(locationNum, tranWarehouseId);
            if (CollectionUtil.isNotEmpty(locationList)) {
                locationList = locationList.stream().sorted(Comparator.comparing(LocationNumVo::getRow).thenComparing(LocationNumVo::getColumn)).collect(Collectors.toList());
            }
        }
        retMap.put("warehouseList", warehouseList);
        retMap.put("locationNumList", locationNumList.stream().filter(CollectionUtil::isNotEmpty).collect(Collectors.toList()));
        retMap.put("locationList", locationList);
        return retMap;
    }


    public Object queryLocationByToolNo(String toolNo, String toolType, String sankType) throws ToolLifeCycleException {
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = checkAssemblyToolTypeExist(toolNo);
        Map<String, Object> retMap = new HashMap<>();
        //根据刀片型号和刀柄型号查询库位信息
        QueryWrapper<ToolConnectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tool_no", toolNo);
        List<ToolConnectEntity> toolConnectEntities = toolConnectMapper.selectList(wrapper);
        List<Map<String, Object>> partTypes = toolConnectEntities.stream().map(this::mapPartTypeVo).collect(Collectors.toList());
//        for (String partType : partTypes) {
//            List<LocationNameVo> locationNameVos = toolForkRespository.getListByToolType(partType);
//            List<Map<String, Object>> locationNames = new ArrayList<>();
//            if (CollectionUtil.isNotEmpty(locationNameVos)) {
//                locationNames = locationNameVos.stream().map(this::getLocationNames).collect(Collectors.toList());
//                retMap.put("toolType", partType);
//                retMap.put("toolLocationList", locationNames);
//                break;
//            }
//        }
//        if(retMap.getOrDefault("toolType" , "").equals("")){
//            buildRetMap(assemblyToolInventoryEntity.getToolType() , retMap , 0);
//        }
        Map<String, Object> paramMap1 = new HashMap<>();
        paramMap1.put("singleToolType", assemblyToolInventoryEntity.getToolType());
        if (StringUtil.isNotEmpty(toolType) && ObjectUtil.isNotNull(toolType)) {
            Map<String, Object> paramMap2 = new HashMap<>();
            paramMap2.put("singleToolType", toolType);
            partTypes.add(paramMap2);
        }
        partTypes.add(paramMap1);

//        if(CollectionUtil.isEmpty(partTypes)){
//
//        }
        if (CollectionUtil.isNotEmpty(partTypes)) {
            partTypes = partTypes.stream().distinct().collect(Collectors.toList());
            partTypes.forEach(paramMap -> {
                paramMap.put("number", ObjectUtil.isNotNull(toolPartRespository.countByPartType(paramMap.get("singleToolType").toString())) ? toolPartRespository.countByPartType(paramMap.get("singleToolType").toString()) : 0);
            });
            partTypes.sort((m1, m2) -> String.valueOf(m2.get("number")).compareTo(String.valueOf(m1.get("number"))));
        }
        retMap.put("toolType", partTypes);


        List<Map<String, Object>> shankTypes = new ArrayList<>();
        Map<String, Object> shankMap1 = new HashMap<>();
        shankMap1.put("singleToolType", assemblyToolInventoryEntity.getShankType());
        if (ObjectUtil.isNotNull(sankType) && StringUtil.isNotEmpty(sankType) && !assemblyToolInventoryEntity.getShankType().equals(sankType)) {
            Map<String, Object> shankMap2 = new HashMap<>();
            shankMap2.put("singleToolType", sankType);
            shankTypes.add(shankMap2);
        }
        shankTypes.add(shankMap1);
        buildRetMap(shankTypes, retMap, 1);
        return retMap;
    }

    private Map<String, Object> mapPartTypeVo(ToolConnectEntity toolConnectEntity) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("singleToolType", toolConnectEntity.getPartType());
        return paramMap;
    }

    @NotNull
    private Map<String, Object> buildRetMap(List<Map<String, Object>> shankTypes, Map<String, Object> retMap, Integer flag) throws ToolLifeCycleException {
//        List<LocationNameVo> locationNameVos = toolForkRespository.getListByToolType(type);
//        List<Map<String, Object>> locationNames = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(locationNameVos)) {
////            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_RECORD_NO_EXIT.getCode(), ToolLifeCycleEx.INVENTORY_RECORD_NO_EXIT.getMsg());
//            locationNames = locationNameVos.stream().map(this::getLocationNames).collect(Collectors.toList());
//        }
//        if (flag == 0) {
//            retMap.put("toolType", type);
//            retMap.put("toolLocationList", locationNames);
//        }
        if (CollectionUtil.isNotEmpty(shankTypes)) {
            shankTypes = shankTypes.stream().distinct().collect(Collectors.toList());
            shankTypes.forEach(paramMap -> {
                paramMap.put("number", ObjectUtil.isNotNull(toolPartRespository.countByPartType(paramMap.get("singleToolType").toString())) ? toolPartRespository.countByPartType(paramMap.get("singleToolType").toString()) : 0);
            });
            shankTypes.sort((m1, m2) -> String.valueOf(m2.get("number")).compareTo(String.valueOf(m1.get("number"))));
        }
        retMap.put("shankType", shankTypes);
        //retMap.put("shankLocationList", locationNames);
        return retMap;
    }

    private Map<String, Object> getLocationNames(LocationNameVo locationNameVo) {
        Map<String, Object> buildMap = new HashMap<>();
        buildMap.put("locationId", locationNameVo.getId());
        buildMap.put("locationName", locationNameVo.getWarehouseName() + "-" + locationNameVo.getLocationNum());
        return buildMap;
    }

    @Transactional
    public synchronized Object inboundUniqueAssemblyTool(InboundAssemblyReq inboundAssemblyReq) throws ToolLifeCycleException {
        ToolPartEntity toolPartEntity = getToolPartEntity(inboundAssemblyReq.getAssemblyUniqueId());
        //修改刀具库位id
        toolPartEntity.setInventoryLocationId(inboundAssemblyReq.getLocationId());
        toolPartMapper.updateById(toolPartEntity);
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOne(inboundAssemblyReq.getLocationId(), toolPartEntity.getToolNo());
        checkCapacity(inboundAssemblyReq.getLocationId(), inboundAssemblyReq.getNumber());
        //修改库位容量
        updateLocationUseCapacity(inboundAssemblyReq.getLocationId(), inboundAssemblyReq.getNumber());
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(inboundAssemblyReq.getNumber(), toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(inboundAssemblyReq.getLocationId());
            toolInventoryLocationEntity.setAssemblyToolInventoryId(assemblyToolInventoryRepository.getIdByToolNo(toolPartEntity.getToolNo()));
            toolInventoryLocationEntity.setPhysicalInventory(inboundAssemblyReq.getNumber());
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
        }
        List<Integer> idList = new ArrayList<>();
        idList.add(toolPartEntity.getId());
        String toolPartParams = buildToolPartParams(toolPartEntity);
        entryExitRecordService.createEntryRecordReload(toolInventoryLocationEntity, inboundAssemblyReq.getNumber(), idList, CommonConstant.INBOUND_CONST, inboundAssemblyReq.getOperator(), inboundAssemblyReq.getBz(), "", "", new Date() , toolPartParams);
        return Boolean.TRUE;
    }

    private String buildToolPartParams(ToolPartEntity toolPartEntity) {
        if(StringUtils.isBlank(toolPartEntity.getParams())){
            return "";
        }
        ToolPartParamsVo toolPartParamsVo = JSONObject.parseObject(toolPartEntity.getParams(), ToolPartParamsVo.class);
        ToolForkInfoCountVo toolForkInfoCountVo1 = new ToolForkInfoCountVo();
        ToolForkInfoCountVo toolForkInfoCountVo2 = new ToolForkInfoCountVo();
        List<ToolForkInfoCountVo> toolPartParamVos = new ArrayList<>();
        toolForkInfoCountVo1.setPartno((toolPartRespository.getPartnoByUniqueId(toolPartParamsVo.getToolType().get(0))));
        toolForkInfoCountVo1.setNumber(toolPartParamsVo.getToolType().size());
        toolForkInfoCountVo2.setPartno((toolPartRespository.getPartnoByUniqueId(toolPartParamsVo.getShankType().get(0))));
        toolForkInfoCountVo2.setNumber(toolPartParamsVo.getShankType().size());
        toolPartParamVos.add(toolForkInfoCountVo1);
        toolPartParamVos.add(toolForkInfoCountVo2);
        return JSONArray.toJSONString(toolPartParamVos);
    }

    @Transactional
    public synchronized Object inboundUniqueTool(InboundUniqueToolReq inboundUniqueToolReq) throws ToolLifeCycleException {
        checkCapacity(inboundUniqueToolReq.getLocationId(), inboundUniqueToolReq.getNumber());
        //修改库位容量
        updateLocationUseCapacity(inboundUniqueToolReq.getLocationId(), inboundUniqueToolReq.getNumber());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOneTool(inboundUniqueToolReq.getLocationId(), inboundUniqueToolReq.getPartno());
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(inboundUniqueToolReq.getNumber(), toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(inboundUniqueToolReq.getLocationId());
            toolInventoryLocationEntity.setToolId(toolForkRespository.getIdByPartNo(inboundUniqueToolReq.getPartno()));
            toolInventoryLocationEntity.setPhysicalInventory(inboundUniqueToolReq.getNumber());
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
        }
        List<Integer> idList = inboundUniqueToolReq.getInboundToolUniqueIds().stream().map(s -> toolPartRespository.getIdByUniqueId(s)).collect(Collectors.toList());
        updateToolPartLocationId(idList, inboundUniqueToolReq.getLocationId());
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inboundUniqueToolReq.getNumber(), idList, CommonConstant.INBOUND_CONST, inboundUniqueToolReq.getOperator(), inboundUniqueToolReq.getBz(), "", "", new Date());
        return Boolean.TRUE;
    }

    @Transactional
    public synchronized Object outboundUniqueTool(InboundUniqueToolReq inboundUniqueToolReq) throws ToolLifeCycleException {
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOneTool(inboundUniqueToolReq.getLocationId(), inboundUniqueToolReq.getPartno());
        if (ObjectUtil.isNull(toolInventoryLocationEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        //校验实际库存数量
        if (ObjectUtil.isNull(toolInventoryLocationEntity.getPhysicalInventory()) || toolInventoryLocationEntity.getPhysicalInventory() == 0 || inboundUniqueToolReq.getInboundToolUniqueIds().size() > toolInventoryLocationEntity.getPhysicalInventory()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getCode(), ToolLifeCycleEx.OUTBOUND_NUMBER_EXCEED.getMsg());
        }
        toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() - inboundUniqueToolReq.getInboundToolUniqueIds().size());
        toolInventoryLocationEntity.setLastUpdateTime(new Date());
        toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
        //库位使用容量修改
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(inboundUniqueToolReq.getLocationId());
        inventoryLocationEntity.setUseCapacity(inventoryLocationEntity.getUseCapacity() - inboundUniqueToolReq.getInboundToolUniqueIds().size());
        //设置库存状态位
        if (inventoryLocationEntity.getUseCapacity() == 0) {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.EMPTY.getCode());
        } else {
            inventoryLocationEntity.setStatus(InventoryStatusEnum.FREE.getCode());
        }
        inventoryLocationRespository.updateInventoryLocationById(inventoryLocationEntity);
        updateWarehouseStatus(inventoryLocationEntity);
        List<Integer> idList = inboundUniqueToolReq.getInboundToolUniqueIds().stream().map(s -> toolPartRespository.getIdByUniqueId(s)).collect(Collectors.toList());
        updateToolPartLocationId(idList, 0);
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inboundUniqueToolReq.getInboundToolUniqueIds().size(), idList, CommonConstant.OUTBOUND_CONST, inboundUniqueToolReq.getOperator(), inboundUniqueToolReq.getBz(), "", "", new Date());
        return Boolean.TRUE;
    }

    private void updateToolPartLocationId(List<Integer> idList, Integer locationId) {
        if (CollectionUtil.isNotEmpty(idList) && ObjectUtil.isNotNull(locationId)) {
            List<ToolPartEntity> toolPartEntities = toolPartRespository.selectByIds(idList);
            toolPartEntities.forEach(toolPartEntity -> toolPartEntity.setInventoryLocationId(locationId));
            toolPartMapper.updateBatchById(toolPartEntities);
        }
    }

    @Transactional
    public synchronized Object inboundUniqueTool(InboundToolReq inboundToolReq) throws ToolLifeCycleException {
        checkCapacity(inboundToolReq.getLocationId(), inboundToolReq.getNumber());
        //修改库位容量
        updateLocationUseCapacity(inboundToolReq.getLocationId(), inboundToolReq.getNumber());
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOneTool(inboundToolReq.getLocationId(), inboundToolReq.getPartno());
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(inboundToolReq.getNumber(), toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(inboundToolReq.getLocationId());
            toolInventoryLocationEntity.setToolId(toolForkRespository.getIdByPartNo(inboundToolReq.getPartno()));
            toolInventoryLocationEntity.setPhysicalInventory(inboundToolReq.getNumber());
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
        }
        List<Integer> idList = inboundToolReq.getInboundTools().stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        updateToolPartLocationId(idList, inboundToolReq.getLocationId());
        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inboundToolReq.getNumber(), idList, CommonConstant.INBOUND_CONST, inboundToolReq.getOperator(), inboundToolReq.getBz(), "", inboundToolReq.getProductionNum(), new Date());
        return Boolean.TRUE;
    }


    private ToolPartEntity getToolPartEntity(String uniqueId) {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id", uniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        return toolPartEntity;
    }

    public String createAssemblyTool(CreateAssemblyToolReq createAssemblyToolReq) throws ToolLifeCycleException {
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(createAssemblyToolReq.getToolNo());
        if (ObjectUtil.isNull(assemblyToolInventoryEntity)) {
            assemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
            BeanUtils.copyProperties(createAssemblyToolReq, assemblyToolInventoryEntity);
            assemblyToolInventoryEntity.setName("总成" + System.currentTimeMillis() + UUIDUtil.getUUID().substring(0, 5));
            assemblyToolInventoryMapper.insert(assemblyToolInventoryEntity);
        }
        return assemblyToolInventoryEntity.getToolNo();
    }

    @Transactional
    public synchronized Object inboundToolPartAssemblyTool(InboundToolPartAssemblyToolReq inboundToolPartAssemblyToolReq) throws ToolLifeCycleException {
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(inboundToolPartAssemblyToolReq.getToolNo());
        //向关系表里面插入记录
        ToolInventoryLocationEntity toolInventoryLocationEntity = insertToolInventoryLocation(inboundToolPartAssemblyToolReq.getNumber(), inboundToolPartAssemblyToolReq.getInventoryLocationId(), assemblyToolInventoryEntity);
        //出库零件记录保存
        List<ToolPartEntity> outboundToolList = insertOutboundToolRecord(inboundToolPartAssemblyToolReq, inboundToolPartAssemblyToolReq.getToolPartno(), inboundToolPartAssemblyToolReq.getToolLocationId(), inboundToolPartAssemblyToolReq.getToolNumber());
        List<ToolPartEntity> outboundShankList = insertOutboundToolRecord(inboundToolPartAssemblyToolReq, inboundToolPartAssemblyToolReq.getShankPartno(), inboundToolPartAssemblyToolReq.getShankLocationId(), inboundToolPartAssemblyToolReq.getShankNumber());
        if (CollectionUtil.isEmpty(outboundShankList) || CollectionUtil.isEmpty(outboundToolList)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        if (outboundToolList.size() < inboundToolPartAssemblyToolReq.getToolNumber() * inboundToolPartAssemblyToolReq.getNumber() || outboundShankList.size() < inboundToolPartAssemblyToolReq.getShankNumber() * inboundToolPartAssemblyToolReq.getNumber()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
//        //库位使用容量修改
//        updateLocationUseCapacity(inboundToolPartAssemblyToolReq.getInventoryLocationId(), inboundToolPartAssemblyToolReq.getNumber());
        //生成唯一编号(库位选择)
        List<ToolPartEntity> toolPartEntityList = toolPartService.buildAssemblyToolPart(toolInventoryLocationEntity, inboundToolPartAssemblyToolReq, assemblyToolInventoryEntity, outboundToolList, outboundShankList);
        String toolPartParams = buildToolPartParams(toolPartEntityList.get(0));
        //生成入库记录
        List<Integer> toolPartIdList = toolPartEntityList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        entryExitRecordService.createEntryRecordReload(toolInventoryLocationEntity, inboundToolPartAssemblyToolReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, inboundToolPartAssemblyToolReq.getOperator(), inboundToolPartAssemblyToolReq.getBz(), "", "", new Date(), toolPartParams);
        return toolPartEntityList.stream().map(ToolPartEntity::getUniqueId).collect(Collectors.toList());
    }

    @Transactional
    List<ToolPartEntity> insertOutboundToolRecord(InboundToolPartAssemblyToolReq inboundToolPartAssemblyToolReq, String partno, Integer locationId, Integer number) throws ToolLifeCycleException {
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOneByToolTypeAndLocationId(partno, locationId);
        ToolForkInfoEntity toolForkInfoEntity = checkToolForkTypeExistByType(partno);
        InBoundOrOutBoundReq inBoundOrOutBoundReq = new InBoundOrOutBoundReq();
        BeanUtils.copyProperties(inboundToolPartAssemblyToolReq, inBoundOrOutBoundReq);
        //根据操作总成数量得到需要的零件数量
        inBoundOrOutBoundReq.setInventoryLocationId(locationId);
        inBoundOrOutBoundReq.setNumber(inBoundOrOutBoundReq.getNumber() * number);
        return outboundTool(inBoundOrOutBoundReq, toolForkInfoEntity, toolInventoryLocationEntity);
    }


    private ToolInventoryLocationEntity insertToolInventoryLocation(Integer number, Integer inventoryLocationId, AssemblyToolInventoryEntity assemblyToolInventoryEntity) throws ToolLifeCycleException {
        ToolInventoryLocationQueryVo queryVo = new ToolInventoryLocationQueryVo();
        queryVo.setAssemblyToolId(assemblyToolInventoryEntity.getId());
        queryVo.setInventoryLocationId(inventoryLocationId);
        ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.queryOne(queryVo);
        if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
            //修改
            updatePhysicalInventory(number, toolInventoryLocationEntity);
        } else {
            //新增
            toolInventoryLocationEntity = new ToolInventoryLocationEntity();
            toolInventoryLocationEntity.setInventoryLocationId(inventoryLocationId);
            toolInventoryLocationEntity.setAssemblyToolInventoryId(assemblyToolInventoryEntity.getId());
            toolInventoryLocationEntity.setPhysicalInventory(number);
            toolInventoryLocationEntity.setLastUpdateTime(new Date());
            toolInventoryLocationMapper.insert(toolInventoryLocationEntity);
        }
        //库位使用容量修改
        updateLocationUseCapacity(inventoryLocationId, number);
        return toolInventoryLocationEntity;
    }


    public void delectInventoryLocation(Integer warehouseId, String delectInventoryLocation) {
        inventoryLocationRespository.delectInventoryLocation(warehouseId, delectInventoryLocation);
    }


    public List<InventoryILocationReq> selectInventoryMessage(Integer warehouseId, String selectMessage) {
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectInventoryLocation(warehouseId, selectMessage);
        Map<Integer, List<InventoryLocationEntity>> o = inventoryLocationEntities.stream().collect(Collectors.groupingBy(InventoryLocationEntity::getRow));
        List<InventoryILocationReq> list1 = new ArrayList<>();
        for (Map.Entry<Integer, List<InventoryLocationEntity>> entry : o.entrySet()) {
            List<InventoryLocationEntity> value = entry.getValue();
            Integer index = entry.getKey();
            //根据列排序
            Collections.sort(value, (a, b) -> {
                return a.getColumn() - b.getColumn();
            });
            InventoryILocationReq inventoryILocationReq = new InventoryILocationReq();
            inventoryILocationReq.setIndex(index);
            inventoryILocationReq.setChild(value);
            list1.add(inventoryILocationReq);
        }
        return list1;
    }

    public void addMachineToolLocation(Integer warehouseId, Integer number) {
        List<InventoryLocationEntity> insertEntities = new ArrayList<>();
        for (int i = 1; i <= number; i++) {
            InventoryLocationEntity inventoryLocationEntity = new InventoryLocationEntity();
            inventoryLocationEntity.setLocationNum(String.valueOf(i));
            inventoryLocationEntity.setLastUpdateTime(new Date());
            inventoryLocationEntity.setStatus(0);
            inventoryLocationEntity.setCapacity(1);
            inventoryLocationEntity.setUseCapacity(0);
            inventoryLocationEntity.setWarehouseId(warehouseId);
            inventoryLocationEntity.setWarehouseName(warehouseRespository.getNameByWarehouseId(warehouseId));
            insertEntities.add(inventoryLocationEntity);
            inventoryLocationRespository.addInventoryLocation(inventoryLocationEntity);
        }
    }

    public Object toolReturnIndex(ToolReturnIndexReq toolReturnIndexReq) {
        ToolConsumptionandUsageAnalysisReq toolConsumptionandUsageAnalysisReq = new ToolConsumptionandUsageAnalysisReq();
        if (StringUtil.isNotEmpty(toolReturnIndexReq.getLocationNum())) {
            toolConsumptionandUsageAnalysisReq.setLocationNum(toolReturnIndexReq.getLocationNum());
        }
        if (StringUtil.isNotEmpty(toolReturnIndexReq.getWarehouseType())) {
            toolConsumptionandUsageAnalysisReq.setWarehouseType(toolReturnIndexReq.getWarehouseType());
        }
        if (ObjectUtil.isNotEmpty(toolReturnIndexReq.getWarehouseId())) {
            toolConsumptionandUsageAnalysisReq.setWarehouseId(toolReturnIndexReq.getWarehouseId());
        }
        List<Integer> inventoryLocationIds = new ArrayList<>();
        if (toolReturnIndexReq.getFlag()) {
            //刀具归还首页
            if (StringUtil.isEmpty(toolReturnIndexReq.getLocationNum()) && StringUtil.isEmpty(toolReturnIndexReq.getWarehouseType()) && ObjectUtil.isEmpty(toolReturnIndexReq.getWarehouseId())) {
                inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNums();
            } else {
                inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNum(toolConsumptionandUsageAnalysisReq);
            }
        } else {
            inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNum(toolConsumptionandUsageAnalysisReq);
        }
        toolReturnIndexReq.setInventoryLocationIds(inventoryLocationIds);
        List<ToolPartEntity> toolPartEntities = toolPartRespository.selectAllList(toolReturnIndexReq);
        List<ToolPartEntity> originalList = new ArrayList<>();
        if (ObjectUtil.isNull(toolReturnIndexReq.getToolLifeLeft())) {
            //归还
            originalList = toolPartEntities.stream().filter(toolPartEntity -> (ObjectUtil.isNotNull(toolPartEntity.getTypeFlag()) && toolPartEntity.getTypeFlag() == 1) || ObjectUtil.isNotNull(toolPartEntity.getCodeScannerFlag()) && toolPartEntity.getCodeScannerFlag() == 1 && toolPartEntity.getIsAssembled() == 0).collect(Collectors.toList());
        } else {
            //报废
            originalList = toolPartEntities.stream().filter(toolPartEntity -> ObjectUtil.isNotNull(toolPartEntity.getTypeFlag()) && toolPartEntity.getTypeFlag() == 1).collect(Collectors.toList());
        }
        List<ToolPartEntity> resultList = new ArrayList<>();
        List<ToolPartEntity> filterList = new ArrayList<>();

        Boolean flag = false;

        if (CollectionUtil.isNotEmpty(originalList)) {
            if (StringUtil.isNotEmpty(toolReturnIndexReq.getToolNo())) {
                originalList = originalList.stream().filter(toolPartEntity -> StringUtil.isNotEmpty(toolPartEntity.getToolNo()) && toolPartEntity.getToolNo().contains(toolReturnIndexReq.getToolNo())).collect(Collectors.toList());
            }

            //通过寿命作为条件过滤
            if (ObjectUtil.isNotNull(toolReturnIndexReq.getToolLifeLeft())) {
                flag = true;
                originalList.forEach(toolPartEntity -> {
                    String remainLife = toolPartEntity.getRemainingLife();
                    String life = toolPartEntity.getLife();
                    if (StringUtil.isNotEmpty(remainLife)) {
                        double remainLifeDouble = Double.parseDouble(remainLife.substring(0, remainLife.length() - 1));
                        double lifeDouble = Double.parseDouble(life.substring(0, life.length() - 1));
                        double filterCondition = remainLifeDouble / lifeDouble;
//                        double filterLeft = (double) toolReturnIndexReq.getToolLifeLeft();
//                        double filterRight = (double) toolReturnIndexReq.getToolLifeRight();
                        if (0 <= filterCondition && filterCondition <= 0.2) {
                            filterList.add(toolPartEntity);
                        }
                    }
                });
            }
            if (flag) {
                //为true是刀具报废首页
                if (CollectionUtil.isNotEmpty(filterList)) {
                    resultList = CommonUtil.pageList(filterList, toolReturnIndexReq.getPageNum(), toolReturnIndexReq.getPageSize());
                }
            } else {
                //为false是刀具归还首页
                if (CollectionUtil.isNotEmpty(originalList)) {
                    resultList = CommonUtil.pageList(originalList, toolReturnIndexReq.getPageNum(), toolReturnIndexReq.getPageSize());
                    if (CollectionUtil.isNotEmpty(resultList)) {
                        resultList.forEach(toolPartEntity -> {
                            if (ObjectUtil.isNotNull(toolPartEntity.getTypeFlag()) && toolPartEntity.getTypeFlag() == 1) {
                                if (StringUtils.isNotBlank(toolPartEntity.getParams())) {
                                    JSONObject jsonObject = JSONObject.parseObject(toolPartEntity.getParams());
                                    List<String> shankTypes = (List<String>) jsonObject.get("shankType");
                                    if (CollectionUtil.isNotEmpty(shankTypes)) {
                                        toolPartEntity.setShankRfid(shankTypes.get(0));
                                    }
                                }
                            } else if (ObjectUtil.isNotNull(toolPartEntity.getTypeFlag()) && toolPartEntity.getTypeFlag() == 0 && ObjectUtil.isNotNull(toolPartEntity.getUniqueId())) {
                                toolPartEntity.setShankRfid(toolPartEntity.getUniqueId());
                            }
                        });
                    }
                }
            }
//            if(CollectionUtil.isNotEmpty(filterList)){
//                resultList = CommonUtil.pageList(filterList, toolReturnIndexReq.getPageNum(), toolReturnIndexReq.getPageSize());
//            }else {
//                resultList = CommonUtil.pageList(originalList, toolReturnIndexReq.getPageNum(), toolReturnIndexReq.getPageSize());
//            }
        }
        Map<String, Object> retMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(resultList)) {
            resultList.forEach(toolPartEntity -> {
//                ToolInventoryVo toolInventoryVo = new ToolInventoryVo();
                buildLocationNameReload(toolPartEntity);
                if (StringUtil.isNotEmpty(toolPartEntity.getToolNo())) {
                    String imageUrl = assemblyToolInventoryRepository.selectImageByToolNo(toolPartEntity.getToolNo());
                    if (StringUtil.isNotEmpty(imageUrl)) {
                        toolPartEntity.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + imageUrl);
                    }
                }
            });
        }
        if (flag) {
            retMap.put("list", resultList);
            retMap.put("total", filterList.size());
        } else {
            retMap.put("list", resultList);
            retMap.put("total", originalList.size());
        }
        return retMap;
    }

    private void buildLocationNameReload(ToolPartEntity toolPartEntity) {
        LocationNameVo locationNameVo = inventoryLocationRespository.queryLocation(toolPartEntity.getId());
        if (locationNameVo != null) {
            StringBuilder stringBuilder = new StringBuilder();
            String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-").append(locationNameVo.getWarehouseName()).append("-库位").append(locationNameVo.getLocationNum()).append("-位置").append(locationNameVo.getRow()).append("-").append(locationNameVo.getColumn()).toString();
//                    toolInventoryVo.setWarehouseName(locationName);
            toolPartEntity.setWarehouseName(locationName);
        }
    }


    @Transactional
    public synchronized Object toolReturn(ToolReturnReq toolReturnReq) throws ToolLifeCycleException {
        ToolPartEntity assemblyToolEntity = handleAssemblyTool(toolReturnReq.getId());
        //设置拆分日志
        buildToolPart(toolReturnReq.getToolUniqueId(), toolReturnReq.getToolReturnOperator());
        buildToolPart(toolReturnReq.getShankUniqueId(), toolReturnReq.getShankReturnOperator());
        ToolPartEntity toolEntity = toolPartRespository.getByUniqueId(toolReturnReq.getToolUniqueId());
        ToolPartEntity shankEntity = toolPartRespository.getByUniqueId(toolReturnReq.getShankUniqueId());
        if (toolReturnReq.getFlag() == 1) {
            //flag为0是刀具归还 为1是刀具报废 刀具报废生成报废日志
            buildDamageLog(Arrays.asList(assemblyToolEntity, toolEntity), toolReturnReq.getToolReturnOperator());
        }
        //给刀片生成报废日志
        InboundToolReq inboundToolReq = new InboundToolReq();
        inboundToolReq.setInboundTools(Collections.singletonList(toolEntity));
        inboundToolReq.setLocationId(toolReturnReq.getToolLocationId());
        inboundToolReq.setPartno(toolEntity.getPartno());
        inboundToolReq.setOperator(toolReturnReq.getToolReturnOperator());
        inboundUniqueTool(inboundToolReq);
        InboundToolReq inboundShankReq = new InboundToolReq();
        inboundShankReq.setInboundTools(Collections.singletonList(shankEntity));
        inboundShankReq.setLocationId(toolReturnReq.getShankLocationId());
        inboundShankReq.setPartno(shankEntity.getPartno());
        inboundShankReq.setOperator(toolReturnReq.getShankReturnOperator());
        inboundUniqueTool(inboundShankReq);
        return Boolean.TRUE;
    }

    @NotNull
    private ToolPartEntity handleAssemblyTool(Integer id) {
        ToolPartEntity assemblyToolEntity = toolPartMapper.selectById(id);
        if (!ObjectUtil.isNull(assemblyToolEntity.getInventoryLocationId()) || assemblyToolEntity.getInventoryLocationId() != 0) {
            //刀具库位不为空出库刀具
            ToolInventoryLocationEntity toolInventoryLocationEntity = toolInventoryLocationRespository.selectOne(assemblyToolEntity.getInventoryLocationId(), assemblyToolEntity.getToolNo());
            if (ObjectUtil.isNotNull(toolInventoryLocationEntity)) {
                toolInventoryLocationEntity.setPhysicalInventory(toolInventoryLocationEntity.getPhysicalInventory() - 1);
                toolInventoryLocationMapper.updateById(toolInventoryLocationEntity);
            }
        }
        assemblyToolEntity.setInventoryLocationId(0);
        assemblyToolEntity.setBackupStatus(0);
        //设置总成状态为拆分
        assemblyToolEntity.setStatus(1);
        return assemblyToolEntity;
    }

//    @Transactional
//    public synchronized Object toolPartReturn(ToolReturnReq toolReturnReq) throws ToolLifeCycleException {
//        ToolPartEntity assemblyToolEntity = handleAssemblyTool(toolReturnReq.getId());
//        //设置拆分日志
//        buildToolPart(toolReturnReq.getToolUniqueId(), toolReturnReq.getToolReturnOperator());
//        buildToolPart(toolReturnReq.getShankUniqueId(), toolReturnReq.getShankReturnOperator());
//        ToolPartEntity toolEntity = toolPartRespository.getByUniqueId(toolReturnReq.getToolUniqueId());
//        ToolPartEntity shankEntity = toolPartRespository.getByUniqueId(toolReturnReq.getShankUniqueId());
//        if (toolReturnReq.getFlag() == 1) {
//            //flag为0是刀具归还 为1是刀具报废 刀具报废生成报废日志
//            buildDamageLog(Arrays.asList(assemblyToolEntity, toolEntity), toolReturnReq.getToolReturnOperator());
//        }
//        //给刀片生成报废日志
//        InboundToolReq inboundToolReq = new InboundToolReq();
//        inboundToolReq.setInboundTools(Collections.singletonList(toolEntity));
//        inboundToolReq.setLocationId(toolReturnReq.getToolLocationId());
//        inboundToolReq.setPartno(toolEntity.getPartno());
//        inboundToolReq.setOperator(toolReturnReq.getToolReturnOperator());
//        inboundUniqueTool(inboundToolReq);
//        InboundToolReq inboundShankReq = new InboundToolReq();
//        inboundShankReq.setInboundTools(Collections.singletonList(shankEntity));
//        inboundShankReq.setLocationId(toolReturnReq.getShankLocationId());
//        inboundShankReq.setPartno(shankEntity.getPartno());
//        inboundShankReq.setOperator(toolReturnReq.getShankReturnOperator());
//        inboundUniqueTool(inboundShankReq);
//        return Boolean.TRUE;
//    }

    @Transactional
    public synchronized Object toolPartDamage(ToolPartDamageReq toolPartDamageReq) throws ToolLifeCycleException {
        //ToolPartEntity assemblyToolEntity = handleAssemblyTool(toolPartDamageReq.getId());
        //设置总成报废日志
        //buildDamageLog(Collections.singletonList(assemblyToolEntity), toolPartDamageReq.getOperator());
        //设置拆分日志
        toolPartDamageReq.getInboundToolReqs().forEach((inboundToolUniqueReq) -> {
            inboundToolUniqueReq.getInboundToolUniqueIds().forEach(uniqueId -> {
                buildToolPart(uniqueId, toolPartDamageReq.getOperator());
                ToolPartEntity toolPartEntity = toolPartRespository.getByUniqueId(uniqueId);
                toolPartEntity.setIsDamage(1);
                toolPartEntity.setDamageTime(new Date());
                buildDamageLog(toolPartEntity, toolPartDamageReq.getOperator());
                toolPartMapper.updateById(toolPartEntity);
                //buildDamageLog(Collections.singletonList(toolPartEntity), toolPartDamageReq.getOperator());
            });
            try {
                inboundToolUniqueReq.setLocationId(inventoryLocationRespository.selectIdByWarehouseName("报废货架"));
                inboundUniqueTool(inboundToolUniqueReq);
            } catch (ToolLifeCycleException e) {
                log.error(e.getCode(), e.getMsg());
            }
        });
        return Boolean.TRUE;
    }

    private void buildDamageLog(ToolPartEntity assemblyTool, String operator) {
        AssemblyDamageLogVo assemblyDamageLogVo = new AssemblyDamageLogVo();
        assemblyDamageLogVo.setOperator(operator);
        assemblyDamageLogVo.setType(CommonConstant.DAMAGE);
        assemblyDamageLogVo.setCreateTime(new Date());
        if (StringUtil.isEmpty(assemblyTool.getDamageLog()) || "[]".equals(assemblyTool.getDamageLog())) {
            //之前无装配记录
            List<AssemblyDamageLogVo> list = new ArrayList<>();
            list.add(assemblyDamageLogVo);
            assemblyTool.setDamageLog(JSONArray.toJSONString(list));
            return;
        }
        //之前有装配记录
        List<AssemblyDamageLogVo> assemblyDamageLogVos = JSONArray.parseArray(assemblyTool.getDamageLog(), AssemblyDamageLogVo.class);
        assemblyDamageLogVos.add(assemblyDamageLogVo);
        assemblyTool.setDamageLog(JSONArray.toJSONString(assemblyDamageLogVos));
    }

    private void buildDamageLog(List<ToolPartEntity> toolPartEntities, String operator) {
        toolPartEntities.forEach(toolPartEntity -> {
            if (toolPartEntity.getIsDamage() == 0) {
                toolPartEntity.setIsDamage(1);
                toolPartEntity.setIsAssembled(0);
                toolPartEntity.setDamageTime(new Date());
                AssemblyDamageLogVo assemblyDamageLogVo = new AssemblyDamageLogVo();
                assemblyDamageLogVo.setCreateTime(new Date());
                assemblyDamageLogVo.setOperator(operator);
                assemblyDamageLogVo.setType(CommonConstant.DAMAGE);
                if (StringUtil.isNotEmpty(toolPartEntity.getLife()) && StringUtil.isNotEmpty(toolPartEntity.getTimeUsage())) {
                    assemblyDamageLogVo.setRemainingLife(Double.parseDouble(toolPartEntity.getLife().substring(0, toolPartEntity.getLife().length() - 1)) - Double.parseDouble(toolPartEntity.getTimeUsage().substring(0, toolPartEntity.getTimeUsage().length() - 1)) + "h");
                }
                toolPartEntity.setDamageLog(JSONObject.toJSONString(assemblyDamageLogVo));
            }
        });
        toolPartMapper.updateBatchById(toolPartEntities);
    }

    private void buildToolPart(String toolUniqueId, String operator) {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id", toolUniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        //修改刀具零件的组装状态
        toolPartEntity.setIsAssembled(0);
        toolPartEntity.setAssemblyToolUniqueId("");
        //设置装配记录
        AssembleLogVo assembleLogVo = new AssembleLogVo();
        assembleLogVo.setOperator(operator);
        assembleLogVo.setType(CommonConstant.UN_ASSEMBLE_TYPE);
        assembleLogVo.setCreateTime(new Date());
        if (StringUtil.isEmpty(toolPartEntity.getLog())) {
            //之前无装配记录
            List<AssembleLogVo> list = new ArrayList<>();
            list.add(assembleLogVo);
            toolPartEntity.setLog(JSONArray.toJSONString(list));
            return;
        }
        //之前有装配记录
        List<AssembleLogVo> assembleLogVos = JSONArray.parseArray(toolPartEntity.getLog(), AssembleLogVo.class);
        assembleLogVos.add(assembleLogVo);
        toolPartEntity.setLog(JSONArray.toJSONString(assembleLogVos));
    }

    @Transactional
    public Object importIToolCabinetStock(List<IToolCabinetStockImport> importData, String operator) {
        //导入智能柜库存信息
        //导入关系表
        List<ToolForkInfoEntity> insertToolForkInfoEntities = insertPartnos(importData);
        //List<InventoryLocationEntity> originalList = inventoryLocationRespository.selectAll();
        //已存在的编号库位编号列表
//        List<String> locationNumList = originalList.stream().map(InventoryLocationEntity::getLocationNum).collect(Collectors.toList());
//        List<InventoryLocationEntity> insertEntities = new ArrayList<>();

        //导入智能柜库位信息(刀具库存信息)
        List<ToolInventoryLocationEntity> toolInventoryLocationEntities = new ArrayList<>();
        importData.stream()
                //.filter(iToolCabinetStockImport -> !locationNumList.contains(iToolCabinetStockImport.getPosition()))
                //.filter(iToolCabinetStockImport -> ObjectUtil.isNotNull(iToolCabinetStockImport.getTypeCode()))
                .forEach(iToolCabinetStockImport -> {
////                    InventoryLocationEntity inventoryLocationEntity = new InventoryLocationEntity();
////                    String position = iToolCabinetStockImport.getPosition();
////                    String[] split = position.split("-");
////                    inventoryLocationEntity.setLocationNum(iToolCabinetStockImport.getPosition());
////                    inventoryLocationEntity.setWarehouseName(split[0]);
////                    inventoryLocationEntity.setWarehouseId(warehouseRespository.getByIdOrName(null, split[0]).getId());
////                    inventoryLocationEntity.setStatus(0);
////                    inventoryLocationEntity.setCapacity(300);
////                    inventoryLocationEntity.setUseCapacity(0);
////                    inventoryLocationEntity.setUseCapacity(iToolCabinetStockImport.getPhysicalInventory());
                    ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(new QueryWrapper<ToolForkInfoEntity>().eq("partno", iToolCabinetStockImport.getPartno()));
//                    ToolInventoryLocationEntity toolInventoryLocationEntity = new ToolInventoryLocationEntity();
//                    toolInventoryLocationEntity.setToolId(toolForkInfoEntity.getId());

                    //List<ToolForkInfoEntity> collect = insertToolForkInfoEntities.stream().filter(toolForkInfoEntity1 -> toolForkInfoEntity1.getPartno().equals(iToolCabinetStockImport.getPartno())).collect(Collectors.toList());
                    List<Integer> ids = toolForkRespository.selectIdByPartno(iToolCabinetStockImport.getPartno());

                    InBoundOrOutBoundTimeReq inBoundOrOutBoundTimeReq = new InBoundOrOutBoundTimeReq();
                    inBoundOrOutBoundTimeReq.setNumber(iToolCabinetStockImport.getPhysicalInventory());
                    inBoundOrOutBoundTimeReq.setBz("");
                    inBoundOrOutBoundTimeReq.setInventoryLocationId(inventoryLocationRespository.queryIdByLocationNum(iToolCabinetStockImport.getPosition()));
                    inBoundOrOutBoundTimeReq.setOperator(operator);
                    inBoundOrOutBoundTimeReq.setPartno(iToolCabinetStockImport.getPartno());
                    inBoundOrOutBoundTimeReq.setCreateTime(new Date());
                    try {
                        inboundLocationTool(inBoundOrOutBoundTimeReq);
                    } catch (ToolLifeCycleException e) {
                        log.error(e.getMessage());
                    }

//                    if(CollectionUtil.isEmpty(ids)&&CollectionUtil.isNotEmpty(insertToolForkInfoEntities)){
//                        List<ToolForkInfoEntity> collect = insertToolForkInfoEntities.stream().filter(toolForkInfoEntity1 -> toolForkInfoEntity1.getPartno().equals(iToolCabinetStockImport.getPartno())).collect(Collectors.toList());
//                        toolInventoryLocationEntity.setToolId(collect.get(0).getId());
//                    }else{
//                        toolInventoryLocationEntity.setToolId(ids.get(0));
//                    }
//                    toolInventoryLocationEntity.setInventoryLocationId(inventoryLocationRespository.queryIdByLocationNum(iToolCabinetStockImport.getPosition()));
//                    toolInventoryLocationEntity.setPhysicalInventory(iToolCabinetStockImport.getPhysicalInventory());
//                    toolInventoryLocationEntity.setSafetyInventory(iToolCabinetStockImport.getSafetyInventory());
//                    toolInventoryLocationEntity.setLastUpdateTime(new Date());
//                    toolInventoryLocationEntity.setStatus(iToolCabinetStockImport.getPhysicalInventory() > iToolCabinetStockImport.getSafetyInventory() ? 1 : 0);
//                    toolInventoryLocationEntities.add(toolInventoryLocationEntity);

                    //安全库存设置
                    if (iToolCabinetStockImport.getSafetyInventory() != 0) {
                        InventoryLocationEntity existLocation = inventoryLocationRespository.selectByLocationNum(iToolCabinetStockImport.getPosition());
                        String param = existLocation.getSafetyInventoryConfigureParam();
                        if (StringUtil.isEmpty(param) || "[]".equals(param)) {
                            //新增一条记录
                            List<SingleWarehouseSafetyInventoryParam> params = new ArrayList<>();
                            SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = new SingleWarehouseSafetyInventoryParam();
                            singleWarehouseSafetyInventoryParam.setPartno(iToolCabinetStockImport.getPartno());
                            singleWarehouseSafetyInventoryParam.setToolNo("");
                            singleWarehouseSafetyInventoryParam.setSafetyInventory(iToolCabinetStockImport.getSafetyInventory());
                            params.add(singleWarehouseSafetyInventoryParam);
                            existLocation.setSafetyInventoryConfigureParam(JSONArray.toJSONString(params));
                        } else {
                            //修改
                            List<SingleWarehouseSafetyInventoryParam> paramList = JSONArray.parseArray(param, SingleWarehouseSafetyInventoryParam.class);
                            boolean flag = false;
                            for (int i = 0; i < paramList.size(); i++) {
                                SingleWarehouseSafetyInventoryParam existParams = paramList.get(i);
                                if (StringUtil.isNotEmpty(existParams.getPartno()) && existParams.getPartno().equals(iToolCabinetStockImport.getPartno())) {
                                    //修改类型安全库存
                                    existParams.setSafetyInventory(iToolCabinetStockImport.getSafetyInventory());
                                    flag = true;
                                }
                            }
                            if (!flag) {
                                SingleWarehouseSafetyInventoryParam singleWarehouseSafetyInventoryParam = new SingleWarehouseSafetyInventoryParam();
                                singleWarehouseSafetyInventoryParam.setPartno(iToolCabinetStockImport.getPartno());
                                singleWarehouseSafetyInventoryParam.setToolNo("");
                                paramList.add(singleWarehouseSafetyInventoryParam);
                                existLocation.setSafetyInventoryConfigureParam(JSONArray.toJSONString(paramList));
                            }
                        }
                        inventoryLocationRespository.updateById(existLocation);
                    }

                    //生成对应数量的sn刀具
//                    if(iToolCabinetStockImport.getPhysicalInventory() != 0){
//                        toolPartService.buildToolUniqueId(toolInventoryLocationEntity ,iToolCabinetStockImport.getPhysicalInventory() ,iToolCabinetStockImport.getPartno(),"");
//                    }

//                    inventoryLocationEntity.setRow(Integer.parseInt(split[1]));
//                    inventoryLocationEntity.setColumn(Integer.parseInt(split[2]));
//                    Map<String, Object> paramMap = new HashMap<>();
//                    paramMap.put("idnr", iToolCabinetStockImport.getType());
//                    paramMap.put("partno", iToolCabinetStockImport.getPartno());
//                    paramMap.put("brand", iToolCabinetStockImport.getBrand());
//                    paramMap.put("toolType", iToolCabinetStockImport.getTypeName());
//                    paramMap.put("unit", iToolCabinetStockImport.getUnit());
//                    paramMap.put("number", 0);
//                    inventoryLocationEntity.setParam(JSONObject.toJSONString(paramMap));
                    //insertEntities.add(inventoryLocationEntity);
                    //inventoryLocationRespository.insert(inventoryLocationEntity);
                });
        //inventoryLocationRespository.insertBatch(insertEntities);
        //toolInventoryLocationMapper.insertBatchSomeColumn(toolInventoryLocationEntities);

        return Boolean.TRUE;
    }

    public List<ToolForkInfoEntity> insertPartnos(List<IToolCabinetStockImport> importData) {
        List<ToolForkInfoEntity> existToolForkInfoEntities = toolForkInfoMapper.selectList(new QueryWrapper<ToolForkInfoEntity>());
        List<String> existPartnos = existToolForkInfoEntities.stream().map(ToolForkInfoEntity::getPartno).collect(Collectors.toList());


        List<ToolForkInfoEntity> insertToolForkInfoEntities = new ArrayList<>();
        importData.stream().distinct().filter(iToolCabinetStockImport -> !existPartnos.contains(iToolCabinetStockImport.getPartno())).forEach(iToolCabinetStockImport -> {
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            toolForkInfoEntity.setIdnr(iToolCabinetStockImport.getType());
            toolForkInfoEntity.setPartType(iToolCabinetStockImport.getType());
            toolForkInfoEntity.setPartno(iToolCabinetStockImport.getPartno());
            //设置类型为未分组
            toolForkInfoEntity.setType(ObjectUtil.isNull(iToolCabinetStockImport.getTypeCode()) ? "A001B004" : iToolCabinetStockImport.getTypeCode());
            toolForkInfoEntity.setBrand(iToolCabinetStockImport.getBrand());
            insertToolForkInfoEntities.add(toolForkInfoEntity);
        });
        if (CollectionUtil.isNotEmpty(insertToolForkInfoEntities)) {
            toolForkInfoMapper.insertBatchSomeColumn(insertToolForkInfoEntities);
        }
        return insertToolForkInfoEntities;
    }

    public void insertPartnosReload1(List<ImportToolForkInfoVo> importForkData) {
        if (CollectionUtil.isEmpty(importForkData)) {
            return;
        }
        List<ToolForkInfoEntity> existToolForkInfoEntities = toolForkInfoMapper.selectList(new QueryWrapper<ToolForkInfoEntity>());
        List<String> existPartnos = existToolForkInfoEntities.stream().map(ToolForkInfoEntity::getPartno).collect(Collectors.toList());


        List<ToolForkInfoEntity> insertToolForkInfoEntities = new ArrayList<>();
        importForkData.stream().distinct().filter(importToolForkInfoVo -> !existPartnos.contains(importToolForkInfoVo.getPartno())).forEach(importToolForkInfoVo -> {
            if (StringUtils.isNotBlank(importToolForkInfoVo.getIdnr())) {
                String[] split = importToolForkInfoVo.getIdnr().split("\\/");
                if (split.length > 1) {
                    importToolForkInfoVo.setIdnr(split[split.length - 1]);
                }
            }
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            toolForkInfoEntity.setIdnr(importToolForkInfoVo.getIdnr());
            toolForkInfoEntity.setPartType(importToolForkInfoVo.getIdnr());
            toolForkInfoEntity.setPartno(importToolForkInfoVo.getPartno());
            //设置类型为未分组
            toolForkInfoEntity.setType("A001B004");
            insertToolForkInfoEntities.add(toolForkInfoEntity);
        });
        if (CollectionUtil.isNotEmpty(insertToolForkInfoEntities)) {
            List<ToolForkInfoEntity> collect = insertToolForkInfoEntities.stream().distinct().collect(Collectors.toList());
            toolForkInfoMapper.insertBatchSomeColumn(collect);
        }
    }

    private void insertPartnosReload(List<FirstStockImport> importData) {
        List<ToolForkInfoEntity> existToolForkInfoEntities = toolForkInfoMapper.selectList(new QueryWrapper<ToolForkInfoEntity>());
        List<String> existPartnos = existToolForkInfoEntities.stream().map(ToolForkInfoEntity::getPartno).collect(Collectors.toList());


        List<ToolForkInfoEntity> insertToolForkInfoEntities = new ArrayList<>();
        importData.stream().distinct().filter(iToolCabinetStockImport -> !existPartnos.contains(iToolCabinetStockImport.getPartno())).forEach(firstStockImport -> {
            ToolForkInfoEntity toolForkInfoEntity = new ToolForkInfoEntity();
            toolForkInfoEntity.setIdnr(firstStockImport.getPartType());
            toolForkInfoEntity.setPartType(firstStockImport.getPartType());
            toolForkInfoEntity.setPartno(firstStockImport.getPartno());
            //设置类型为未分组
            toolForkInfoEntity.setType("A001B004");
            insertToolForkInfoEntities.add(toolForkInfoEntity);
        });
        if (CollectionUtil.isNotEmpty(insertToolForkInfoEntities)) {
            toolForkInfoMapper.insertBatchSomeColumn(insertToolForkInfoEntities);
        }
    }


    public Object qryAssemblyToolDetail(String uniqueId) {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id", uniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        AssemblyDetailVo assemblyDetailVo = new AssemblyDetailVo();
        LocationNameVo locationNameById = inventoryLocationRespository.getLocationNameById(toolPartEntity.getInventoryLocationId(), "");
        if (!ObjectUtil.isNull(locationNameById)) {
            assemblyDetailVo.setAssemblyLocationId(locationNameById.getId());
            assemblyDetailVo.setLocation(locationNameById.getWarehouseName() + "-" + locationNameById.getLocationNum());
        } else {
            assemblyDetailVo.setAssemblyLocationId(0);
            assemblyDetailVo.setLocation("");
        }
        assemblyDetailVo.setName(toolPartRespository.getNameByToolNo(toolPartEntity.getToolNo()));
        String params = toolPartEntity.getParams();
        JSONObject jsonObject = JSONObject.parseObject(params);
        List<String> toolTypes = (List<String>) jsonObject.get("toolType");
        List<AssembleMaterialPartVo> toolParts = new ArrayList<>();
        List<AssembleMaterialPartVo> shankParts = new ArrayList<>();
        toolTypes.forEach(toolUniqueId -> {
            AssembleMaterialPartVo toolPart = toolPartRespository.selectByUniqueId(toolUniqueId);
            toolPart.setLocationName(toolLieService.getLocationNameByLocationId(toolPart.getLocationId(), ""));
            toolPart.setTypeName(typeItemRepository.getTypeNameByType(toolPart.getType()));
            toolPart.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + toolPart.getImage());
            toolParts.add(toolPart);
        });
        assemblyDetailVo.setToolParts(toolParts);
        List<String> shankTypes = (List<String>) jsonObject.get("shankType");
        shankTypes.forEach(shankUniqueId -> {
            AssembleMaterialPartVo shankPart = toolPartRespository.selectByUniqueId(shankUniqueId);
            shankPart.setLocationName(toolLieService.getLocationNameByLocationId(shankPart.getLocationId(), ""));
            shankPart.setTypeName(typeItemRepository.getTypeNameByType(shankPart.getTypeName()));
            shankPart.setImage(minioProp.getBaseUrl() + minioProp.getBucketName() + "/" + shankPart.getImage());
            shankParts.add(shankPart);
        });
        assemblyDetailVo.setShankParts(shankParts);
        return assemblyDetailVo;
    }

    @Transactional
    public Object toolPartReturn(ToolPartReturnReq toolPartReturnReq) {
        if (CollectionUtil.isNotEmpty(toolPartReturnReq.getInboundUniqueToolReqs())) {
            toolPartReturnReq.getInboundUniqueToolReqs().stream().forEach(inboundUniqueToolReq -> {
                try {
                    inboundUniqueTool(inboundUniqueToolReq);
                } catch (ToolLifeCycleException e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
            });
        }
        return Boolean.TRUE;
    }

    public Object editLocationSafetyInventory(WarehouseSafetyInventoryParamReq warehouseSafetyInventoryParamReq) {
//        List<SingleWarehouseSafetyInventoryParam> collect = warehouseSafetyInventoryParamReq.getSafetyInventoryParams().stream().filter(distinctByKey(SingleWarehouseSafetyInventoryParam::getToolNo)).collect(Collectors.toList());
//        List<SingleWarehouseSafetyInventoryParam> collect1 = warehouseSafetyInventoryParamReq.getSafetyInventoryParams().stream().filter(distinctByKey(SingleWarehouseSafetyInventoryParam::getPartno)).collect(Collectors.toList());
//        //配置仓库安全库存
//        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(warehouseSafetyInventoryParamReq.getId());
//        if (ObjectUtil.isNotNull(inventoryLocationEntity)) {
//            inventoryLocationEntity.setSafetyInventoryConfigureParam(JSONObject.toJSONString(collect1));
//            inventoryLocationRespository.updateById(inventoryLocationEntity);
//            return Boolean.TRUE;
//        }
//        return Boolean.FALSE;
        List<SingleWarehouseSafetyInventoryParam> updateList = warehouseSafetyInventoryParamReq.getSafetyInventoryParams();
        //List<SingleWarehouseSafetyInventoryParam> collect = warehouseSafetyInventoryParamReq.getSafetyInventoryParams().stream().filter(distinctByKey(SingleWarehouseSafetyInventoryParam::getToolNo)).collect(Collectors.toList());
        //List<SingleWarehouseSafetyInventoryParam> updateList = collect.stream().filter(distinctByKey(SingleWarehouseSafetyInventoryParam::getPartno)).collect(Collectors.toList());
        //配置仓库安全库存
        InventoryLocationEntity inventoryLocationEntity = inventoryLocationRespository.getById(warehouseSafetyInventoryParamReq.getId());
        String safetyInventoryConfigureParam = inventoryLocationEntity.getSafetyInventoryConfigureParam();
        List<SingleWarehouseSafetyInventoryParam> originList = new ArrayList<>();
        if (StringUtil.isNotEmpty(safetyInventoryConfigureParam)) {
            originList = JSONArray.parseArray(inventoryLocationEntity.getSafetyInventoryConfigureParam(), SingleWarehouseSafetyInventoryParam.class);
        }
        SafetyInventoryLogic safetyInventoryLogic = new SafetyInventoryLogic(originList, updateList);
        safetyInventoryLogic.buildSafetyInventoryDo();
        SafetyInventoryDo safetyInventoryDo = safetyInventoryLogic.getSafetyInventoryDo();
        List<SingleWarehouseSafetyInventoryParam> persistance = persistance(safetyInventoryDo, originList);
        inventoryLocationEntity.setSafetyInventoryConfigureParam(JSONObject.toJSONString(persistance));
        inventoryLocationRespository.updateById(inventoryLocationEntity);
        return Boolean.TRUE;
    }

    public Object qryLocation(String locationNum) {
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.qryLocation(locationNum);
        //按照locationNum分组
        if (CollectionUtil.isEmpty(inventoryLocationEntities)) {
            return new ArrayList<>();
        }
        //根据货架分组
        Map<Integer, List<InventoryLocationEntity>> warehouseGroupMap = inventoryLocationEntities.stream().filter(inventoryLocationEntity -> ObjectUtil.isNotNull(inventoryLocationEntity.getWarehouseId())).collect(Collectors.groupingBy(InventoryLocationEntity::getWarehouseId));
        List<WarehouseLocationGroupVo> resultList = new ArrayList<>();
        if (!warehouseGroupMap.isEmpty()) {
            warehouseGroupMap.forEach((key, value) -> {
                WarehouseLocationGroupVo warehouseLocationGroupVo = new WarehouseLocationGroupVo();
                warehouseLocationGroupVo.setTypeName(warehouseItemRepository.getTypeNameByType(key));
                warehouseLocationGroupVo.setChildren(value);
                warehouseLocationGroupVo.setWarehouseId(key);
                warehouseLocationGroupVo.setWarehouseName(warehouseRespository.getNameByWarehouseId(key));
                resultList.add(warehouseLocationGroupVo);
            });
        }
        return resultList;
    }

    public Object backupAssemblyTool(BackupAssemblyToolReq backupAssemblyToolReq) throws ToolLifeCycleException {
        QueryWrapper<AssemblyToolInventoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tool_no", backupAssemblyToolReq.getToolNo());
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(assemblyToolInventoryEntity)) {
            assemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
            assemblyToolInventoryEntity.setName("总成" + System.currentTimeMillis() + UUIDUtil.getUUID().substring(0, 5));
            assemblyToolInventoryEntity.setType("铣削刀具");
            assemblyToolInventoryEntity.setToolNumber(1);
            assemblyToolInventoryEntity.setShankNumber(1);
            assemblyToolInventoryEntity.setToolType(backupAssemblyToolReq.getToolType());
            assemblyToolInventoryEntity.setShankType(backupAssemblyToolReq.getShankType());
            assemblyToolInventoryMapper.insert(assemblyToolInventoryEntity);
            //throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_NO_EXIST.getCode(), ToolLifeCycleEx.TOOL_NO_EXIST.getMsg());
        }
        if (CollectionUtil.isEmpty(backupAssemblyToolReq.getToolUniqueIds()) || CollectionUtil.isEmpty(backupAssemblyToolReq.getShankUniqueIds()) || toolPartService.checkUniqueIds(Stream.concat(backupAssemblyToolReq.getToolUniqueIds().stream(), backupAssemblyToolReq.getShankUniqueIds().stream()))) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getCode(), ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getMsg());
        }
        toolPartService.checkUniqueIds(Stream.concat(backupAssemblyToolReq.getToolUniqueIds().stream(), backupAssemblyToolReq.getShankUniqueIds().stream()));
        ToolPartEntity toolEntity = outBoundToolPart(backupAssemblyToolReq.getToolUniqueIds().get(0), backupAssemblyToolReq.getOperator());
        ToolPartEntity shankEntity = outBoundToolPart(backupAssemblyToolReq.getShankUniqueIds().get(0), backupAssemblyToolReq.getOperator());
        ToolPartEntity toolPartEntity = new ToolPartEntity();
        String uniqueId = toolPartService.generateAssemblyToolUniqueIdPrefix(assemblyToolInventoryEntity.getType()) + "." + assemblyToolInventoryEntity.getToolNo() + "." + toolPartService.generateTimeCode() + "." + CommonUtil.randomNumber();
        toolPartEntity.setUniqueId(uniqueId);
        //toolPartEntity.setInventoryLocationId(toolInventoryLocationEntity.getInventoryLocationId());
        toolPartEntity.setToolNo(assemblyToolInventoryEntity.getToolNo());
        toolPartEntity.setIsDamage(CommonConstant.IS_NOT_DAMAGE);
        toolPartEntity.setTypeFlag(CommonConstant.ASSEMBLY_TOOL_TYPE_FLAG);
        toolPartEntity.setImage(assemblyToolInventoryEntity.getImage());
        toolPartEntity.setBackupStatus(1);
        //toolPartEntity.setSubprogramName(backupAssemblyToolReq.getSubprogramName());
        toolPartEntity.setBackupMachineToolTaskId(backupAssemblyToolReq.getId());
        toolPartEntity.setToolLength(backupAssemblyToolReq.getToolLength());
        toolPartEntity.setRadius(backupAssemblyToolReq.getRadius());
        //TO DO 刀具寿命设置
        buildToolLife(toolPartEntity, toolEntity);
        toolPartService.buildAssembleLog(toolPartEntity, backupAssemblyToolReq.getOperator());
        toolPartService.buildAssemlyMaterialList2(Arrays.asList(toolEntity), Arrays.asList(shankEntity), toolPartEntity, uniqueId, backupAssemblyToolReq.getOperator());
        toolPartMapper.insert(toolPartEntity);
        //入库备刀库位
        List<LocationNumVo> locationNumVos = inventoryLocationRespository.selectLocationByLocationNum("备刀区", null);
        if (CollectionUtil.isNotEmpty(locationNumVos)) {
            InboundAssemblyReq inboundAssemblyReq = new InboundAssemblyReq();
            inboundAssemblyReq.setAssemblyUniqueId(uniqueId);
            inboundAssemblyReq.setLocationId(ObjectUtil.isNotNull(backupAssemblyToolReq.getLocationid()) ? backupAssemblyToolReq.getLocationid() : locationNumVos.get(0).getLocationId());
            inboundAssemblyReq.setBz("");
            inboundAssemblyReq.setOperator(backupAssemblyToolReq.getOperator());
            inboundAssemblyReq.setNumber(1);
            inboundUniqueAssemblyTool(inboundAssemblyReq);
        }

        return StringUtil.isNotEmpty(uniqueId) ? uniqueId : "";
    }

    private void buildToolLife(ToolPartEntity toolPartEntity, ToolPartEntity toolEntity) {
        QueryWrapper<ToolLifeEntity> toolLifewrapper = new QueryWrapper<>();
        toolLifewrapper.eq("classify", toolPartEntity.getToolNo());
        toolLifewrapper.eq("type_flag", 1);
        ToolLifeEntity toolLifeEntity = toolLifeMapper.selectOne(toolLifewrapper);
        if (ObjectUtil.isNull(toolLifeEntity)) {
            //查询组成所用零件配置的寿命
            QueryWrapper<ToolLifeEntity> toolwrapper = new QueryWrapper<>();
            toolwrapper.eq("classify", toolPartEntity.getPartno());
            toolwrapper.eq("type_flag", 0);
            ToolLifeEntity toolLifeEntity1 = toolLifeMapper.selectOne(toolLifewrapper);
            if (ObjectUtil.isNotNull(toolLifeEntity1)) {
                toolPartEntity.setLife(toolLifeEntity1.getLife() + "h");
                toolPartEntity.setRemainingLife(toolLifeEntity1.getLife() + "h");
                toolPartEntity.setTimeUsage("0h");
                toolPartEntity.setRemainingLifeRate((long) 100);
            } else {
                toolPartEntity.setLife("60h");
                toolPartEntity.setRemainingLife("60h");
                toolPartEntity.setTimeUsage("0h");
                toolPartEntity.setRemainingLifeRate((long) 100);
            }
        } else {
            toolPartEntity.setLife(toolLifeEntity.getLife() + "h");
            toolPartEntity.setRemainingLife(toolLifeEntity.getLife() + "h");
            toolPartEntity.setTimeUsage("0h");
            toolPartEntity.setRemainingLifeRate((long) 100);
        }
    }

    public Object backupAssemblyToolReload(BackupAssemblyToolReq backupAssemblyToolReq) throws ToolLifeCycleException {
        QueryWrapper<AssemblyToolInventoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tool_no", backupAssemblyToolReq.getToolNo());
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectOne(wrapper);
//        if (ObjectUtil.isNull(assemblyToolInventoryEntity)) {
//            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_NO_EXIST.getCode(), ToolLifeCycleEx.TOOL_NO_EXIST.getMsg());
//        }
        if (CollectionUtil.isEmpty(backupAssemblyToolReq.getToolUniqueIds()) || CollectionUtil.isEmpty(backupAssemblyToolReq.getShankUniqueIds()) || toolPartService.checkUniqueIds(Stream.concat(backupAssemblyToolReq.getToolUniqueIds().stream(), backupAssemblyToolReq.getShankUniqueIds().stream()))) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getCode(), ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getMsg());
        }
        if(toolPartService.checkUniqueIds(Stream.concat(backupAssemblyToolReq.getToolUniqueIds().stream(), backupAssemblyToolReq.getShankUniqueIds().stream()))){
            throw new ToolLifeCycleException(backupAssemblyToolReq.getId()+"", ToolLifeCycleEx.TOOL_UNIQUE_ID_NO_EXIST.getMsg());
        }
//        ToolPartEntity toolEntity = outBoundToolPart(backupAssemblyToolReq.getToolUniqueIds().get(0) , backupAssemblyToolReq.getOperator());
//        ToolPartEntity shankEntity = outBoundToolPart(backupAssemblyToolReq.getShankUniqueIds().get(0) , backupAssemblyToolReq.getOperator());
        ToolPartEntity toolEntity = toolPartService.getByUniqueId(backupAssemblyToolReq.getToolUniqueIds().get(0));
        ToolPartEntity shankEntity = toolPartService.getByUniqueId(backupAssemblyToolReq.getShankUniqueIds().get(0));
        if (ObjectUtil.isNull(assemblyToolInventoryEntity)) {
            AssemblyToolInventoryEntity insertEntity = new AssemblyToolInventoryEntity();
            insertEntity.setShankType(shankEntity.getIdnr());
            insertEntity.setToolNo(backupAssemblyToolReq.getToolNo());
            insertEntity.setToolType(toolEntity.getIdnr());
            insertEntity.setType("铣削刀具");
            insertEntity.setName("总成" + UUIDUtil.getUUID());
            insertEntity.setToolNumber(1);
            insertEntity.setShankNumber(1);
            assemblyToolInventoryMapper.insert(insertEntity);
        }else if(ObjectUtil.isNotNull(assemblyToolInventoryEntity) && (!assemblyToolInventoryEntity.getShankType().equals(shankEntity.getIdnr()) || !assemblyToolInventoryEntity.getToolType().equals(toolEntity.getIdnr()))){
            assemblyToolInventoryEntity.setToolType(toolEntity.getIdnr());
            assemblyToolInventoryEntity.setShankType(shankEntity.getIdnr());
            assemblyToolInventoryMapper.updateById(assemblyToolInventoryEntity);
        }
        //判断刀柄的rfid确认是否需要出库
        if (ObjectUtil.isNotNull(shankEntity.getInventoryLocationId()) && shankEntity.getInventoryLocationId() > 0) {
            //执行刀柄出库操作
            InboundUniqueToolReq inboundUniqueToolReq = new InboundUniqueToolReq();
            inboundUniqueToolReq.setInboundToolUniqueIds(Arrays.asList(shankEntity.getUniqueId()));
            inboundUniqueToolReq.setLocationId(shankEntity.getInventoryLocationId());
            inboundUniqueToolReq.setPartno(shankEntity.getPartno());
            inboundUniqueToolReq.setOperator(backupAssemblyToolReq.getOperator());
            outboundUniqueTool(inboundUniqueToolReq);
        }
        ToolPartEntity toolPartEntity = new ToolPartEntity();
        String uniqueId = toolPartService.generateAssemblyToolUniqueIdPrefix("铣削刀具") + "." + backupAssemblyToolReq.getToolNo() + "." + toolPartService.generateTimeCode() + "." + CommonUtil.randomNumber();
        toolPartEntity.setUniqueId(uniqueId);
        //toolPartEntity.setInventoryLocationId(toolInventoryLocationEntity.getInventoryLocationId());
        toolPartEntity.setToolNo(backupAssemblyToolReq.getToolNo());
        toolPartEntity.setIsDamage(CommonConstant.IS_NOT_DAMAGE);
        toolPartEntity.setTypeFlag(CommonConstant.ASSEMBLY_TOOL_TYPE_FLAG);
        if (ObjectUtil.isNotNull(assemblyToolInventoryEntity)) {
            toolPartEntity.setImage(assemblyToolInventoryEntity.getImage());
        }
        toolPartEntity.setBackupStatus(1);
        //toolPartEntity.setSubprogramName(backupAssemblyToolReq.getSubprogramName());
        toolPartEntity.setBackupMachineToolTaskId(backupAssemblyToolReq.getId());
        toolPartEntity.setToolLength(backupAssemblyToolReq.getToolLength());
        toolPartEntity.setRadius(backupAssemblyToolReq.getRadius());
        //TO DO 刀具寿命设置
        QueryWrapper<ToolLifeEntity> toolLifewrapper = new QueryWrapper<>();
        toolLifewrapper.eq("classify", toolPartEntity.getToolNo());
        toolLifewrapper.eq("type_flag", 1);
        ToolLifeEntity toolLifeEntity = toolLifeMapper.selectOne(toolLifewrapper);
        if (ObjectUtil.isNotNull(toolLifeEntity)) {
            toolPartEntity.setLife(toolLifeEntity.getLife() + "h");
            toolPartEntity.setRemainingLife(toolLifeEntity.getLife() + "h");
            toolPartEntity.setTimeUsage("0h");
            toolPartEntity.setRemainingLifeRate((long) 100);
        } else {
            toolPartEntity.setLife("60h");
            toolPartEntity.setRemainingLife("60h");
            toolPartEntity.setTimeUsage("0h");
            toolPartEntity.setRemainingLifeRate((long) 100);
        }
        toolPartService.buildAssembleLog(toolPartEntity, backupAssemblyToolReq.getOperator());
        toolPartService.buildAssemlyMaterialList2(Arrays.asList(toolEntity), Arrays.asList(shankEntity), toolPartEntity, uniqueId, backupAssemblyToolReq.getOperator());
        toolPartMapper.insert(toolPartEntity);
        //入库备刀库位
        List<LocationNumVo> locationNumVos = inventoryLocationRespository.selectLocationByLocationNum("备刀区", null);
        if (CollectionUtil.isNotEmpty(locationNumVos)) {
            InboundAssemblyReq inboundAssemblyReq = new InboundAssemblyReq();
            inboundAssemblyReq.setAssemblyUniqueId(uniqueId);
            inboundAssemblyReq.setLocationId(ObjectUtil.isNotNull(backupAssemblyToolReq.getLocationid()) ? backupAssemblyToolReq.getLocationid() : locationNumVos.get(0).getLocationId());
            inboundAssemblyReq.setBz("");
            inboundAssemblyReq.setOperator(backupAssemblyToolReq.getOperator());
            inboundAssemblyReq.setNumber(1);
            inboundUniqueAssemblyTool(inboundAssemblyReq);
        }

        return StringUtil.isNotEmpty(uniqueId) ? uniqueId : "";
    }

    @NotNull
    private ToolPartEntity outBoundToolPart(String uniqueId, String operator) throws ToolLifeCycleException {
        ToolPartEntity toolPartEntity = toolPartService.getByUniqueId(uniqueId);
        InBoundOrOutBoundReq outBoundToolReq = new InBoundOrOutBoundReq();
        outBoundToolReq.setNumber(1);
        outBoundToolReq.setOperator(operator);
        outBoundToolReq.setPartno(toolPartEntity.getPartno());
        outBoundToolReq.setInventoryLocationId(toolPartEntity.getInventoryLocationId());
        outboundLocationTool(outBoundToolReq);
        return toolPartEntity;
    }


    public Object backupUniqueIdAssemblyTool(String uniqueId, Integer id, String subprogramName, String toolLength, String radius, String operator, Integer locationId) throws ToolLifeCycleException {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id", uniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(toolPartEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_NO_EXIST.getCode(), ToolLifeCycleEx.TOOL_NO_EXIST.getMsg());
        }
        //判断是否需要出库
        if (ObjectUtil.isNotNull(toolPartEntity.getInventoryLocationId()) && toolPartEntity.getInventoryLocationId() > 0) {
            OutboundUniqueAssemblyReq outboundUniqueAssemblyReq = buildReq(toolPartEntity);
            outboundUniqueAssemblyReq.setOperator(operator);
            outboundUniqueAssemblyTool(outboundUniqueAssemblyReq);
        }
        toolPartEntity.setBackupStatus(1);
        toolPartEntity.setToolLength(toolLength);
        toolPartEntity.setRadius(radius);
        toolPartEntity.setBackupMachineToolTaskId(id);
        toolPartEntity.setSubprogramName(subprogramName);
        //入库备刀库位
        List<LocationNumVo> locationNumVos = inventoryLocationRespository.selectLocationByLocationNum("备刀区", null);
        if (CollectionUtil.isNotEmpty(locationNumVos)) {
            InboundAssemblyReq inboundAssemblyReq = new InboundAssemblyReq();
            inboundAssemblyReq.setAssemblyUniqueId(uniqueId);
            inboundAssemblyReq.setLocationId(ObjectUtil.isNotNull(locationId) ? locationId : locationNumVos.get(0).getLocationId());
            inboundAssemblyReq.setBz("");
            inboundAssemblyReq.setOperator(operator);
            inboundAssemblyReq.setNumber(1);
            inboundUniqueAssemblyTool(inboundAssemblyReq);
        }
        //查询是否存在记录
        Date configureDate = CommonUtil.getTimeBeforeConfigure(Integer.parseInt(SystemInit.configurationMap.getOrDefault("minutesToPrevious" , 180).toString()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(configureDate);
        ToolParamCacheEntity toolParamCacheEntity = null;
        String toolNo = toolPartEntity.getToolNo();
        //查询是否有绑定值
        toolParamCacheEntity = toolParamCacheRepository.getBySelectedFlag(toolNo, format , subprogramName);
        if(ObjectUtil.isNull(toolParamCacheEntity) || (ObjectUtil.isNotNull(toolParamCacheEntity)&&ObjectUtil.isNull(toolParamCacheEntity.getId()))){
            //没有绑定值则查询普通值
            toolParamCacheEntity = toolParamCacheRepository.selectParamByToolNo(toolNo, format);
        }
        if (ObjectUtil.isNotNull(toolParamCacheEntity)) {
            //选择锁定
            toolParamCacheRepository.updateRecordSelectedFlag(toolParamCacheEntity.getId() , 1 , subprogramName);
            toolPartEntity.setToolLength(toolParamCacheEntity.getLength() + "");
            toolPartEntity.setRadius(toolParamCacheEntity.getRadius() + "");
        }
        toolPartMapper.updateById(toolPartEntity);
        return Boolean.TRUE;
    }

    private OutboundUniqueAssemblyReq buildReq(ToolPartEntity toolPartEntity) {
        OutboundUniqueAssemblyReq outboundUniqueAssemblyReq = new OutboundUniqueAssemblyReq();
        UniqueAssemblyToolVo uniqueAssemblyToolVo = new UniqueAssemblyToolVo();
        uniqueAssemblyToolVo.setUniqueId(toolPartEntity.getUniqueId());
        uniqueAssemblyToolVo.setToolNo(toolPartEntity.getToolNo());
        uniqueAssemblyToolVo.setInventoryLocationId(toolPartEntity.getInventoryLocationId());
        outboundUniqueAssemblyReq.setBatchAssemblyTool(Arrays.asList(uniqueAssemblyToolVo));
        return outboundUniqueAssemblyReq;
    }

    public Object countNumberByLocationId(Integer id) {
        Integer number = inventoryLocationRespository.countNumberByLocationId(id);
        return ObjectUtil.isNotNull(number) ? number : 0;
    }

    public Object editParamByUniqueId(String radius, String toolLength, String life, String uniqueId) {
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("unique_id", uniqueId);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        toolPartEntity.setLife(life + "h");
        toolPartEntity.setRadius(radius);
        toolPartEntity.setToolLength(toolLength);
        toolPartMapper.updateById(toolPartEntity);
        return Boolean.TRUE;
    }

    public Object queryBackUpLocationId() {
        return inventoryLocationRespository.selectBackUpLocation();
    }

    public Object selectCountByToolType(String toolType) {
        Map<String, Integer> retMap = new HashMap<>();
        //统计一级库库存情况和智能柜库存情况
        Integer aCount = toolPartRespository.selectCountByToolTypeGroup(toolType, "A001");
        retMap.put("firstLibrary", ObjectUtil.isNotNull(aCount) ? aCount : 0);
        Integer bCount = toolPartRespository.selectCountByToolTypeGroup(toolType, "A002");
        retMap.put("secLibrary", ObjectUtil.isNotNull(bCount) ? bCount : 0);
        return retMap;
    }

    public Boolean firstStockImport(List<FirstStockImport> importData) {
        if (CollectionUtil.isEmpty(importData)) {
            return Boolean.TRUE;
        }
        //去重并将新物料编码填入表中
        insertPartnosReload(importData);
        //执行入库
        importData.forEach(firstStockImport -> {
            InBoundOrOutBoundReloadReq inBoundOrOutBoundReloadReq = new InBoundOrOutBoundReloadReq();
            inBoundOrOutBoundReloadReq.setNumber(firstStockImport.getNumber());
            inBoundOrOutBoundReloadReq.setBz(firstStockImport.getBz());
            inBoundOrOutBoundReloadReq.setOperator(firstStockImport.getOperator());
            inBoundOrOutBoundReloadReq.setPartno(firstStockImport.getPartno());
            //设置入库货架以及入库时间
            if (ObjectUtil.isNull(firstStockImport.getWarehouse())) {
                return;
            }
            inBoundOrOutBoundReloadReq.setWarehouseId(warehouseRespository.selectWarehouseId(firstStockImport.getWarehouse().substring(0, 1) + "货架"));
            if (ObjectUtil.isNotNull(firstStockImport.getCreateTime())) {
                CommonUtil.transferTime(firstStockImport.getCreateTime());
                inBoundOrOutBoundReloadReq.setCreateTime(new Date());
            }
            try {
                inboundLocationToolReload(inBoundOrOutBoundReloadReq);
            } catch (ToolLifeCycleException e) {
                log.error(e.getMessage());
            }
        });
        return Boolean.TRUE;
    }


    public Object backupBatchTool(BackupBatchToolReq backupBatchToolReq) throws ToolLifeCycleException {
        if (CollectionUtil.isNotEmpty(backupBatchToolReq.getBackupBatchTool())) {
            for (BackupBatchToolSingleReq backupBatchToolSingleReq : backupBatchToolReq.getBackupBatchTool()) {
                if (StringUtil.isNotEmpty(backupBatchToolSingleReq.getAssemblyToolRfid())) {
                    try{
                        backupUniqueIdAssemblyTool(backupBatchToolSingleReq.getAssemblyToolRfid(), backupBatchToolSingleReq.getId(), backupBatchToolSingleReq.getSubprogramName(), backupBatchToolSingleReq.getToolLength(), backupBatchToolSingleReq.getRadius(), backupBatchToolSingleReq.getOperator(), backupBatchToolSingleReq.getLocationid());
                    }catch (ToolLifeCycleException ex){
                        log.error(ex.getCode() , ex.getMsg());
                    }
                } else if (CollectionUtil.isNotEmpty(backupBatchToolSingleReq.getToolUniqueIds()) && CollectionUtil.isNotEmpty(backupBatchToolSingleReq.getShankUniqueIds())) {
                    try{
                        backupAssemblyToolReload(backupBatchToolSingleReq);
                    }catch (ToolLifeCycleException ex){
                        log.error(ex.getCode() , ex.getMsg());
                    }
                }
            }
        }
        return Boolean.TRUE;
    }

    @Transactional
    public synchronized Object selectByRecordReload(String toolType, Integer id , String groupId) {
        //加上类型型号的校验
        QueryWrapper<ToolForkInfoEntity> toolForkWrapper = new QueryWrapper<>();
        toolForkWrapper.eq("idnr" , toolType);
        List<ToolForkInfoEntity> toolForkInfoEntities = toolForkInfoMapper.selectList(toolForkWrapper);
        if (CollectionUtil.isEmpty(toolForkInfoEntities)) {
            return "1";
        }
        String partno = toolForkInfoEntities.get(0).getPartno();

        //增加查询之前被该任务锁定的sn刀片或sn刀具
        QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("selected_task_id" , id);
        wrapper.eq("select_group_id" , groupId);
        wrapper.eq("type_flag" , 0);
        ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(toolPartEntity) && StringUtils.isNotBlank(toolPartEntity.getUniqueId())){
            //toolPartRespository.updateSelectedFlagById(toolPartEntity.getUniqueId(), 1, id, groupId);
            return toolPartEntity.getUniqueId();
        }

        List<Integer> recordIds = new ArrayList<>();

        Integer cycleRecordTime = Integer.parseInt(SystemInit.configurationMap.getOrDefault("cycleRecordTime" , 1440).toString());
        Date configureDate = CommonUtil.getTimeBeforeConfigure(cycleRecordTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(configureDate);

        recordIds = toolPartRespository.selectByRecordReload1(toolType, format, WarehouseConstant.INTELLIGENT_TOOL_CABINET);

        List<ToolPartEntity> toolIdss = toolPartRespository.selectByRecordReload2(partno ,format ,  Arrays.asList(WarehouseConstant.INTELLIGENT_TOOL_CABINET , WarehouseConstant.FIRST_TOOL_CABINET));
        if (CollectionUtil.isNotEmpty(recordIds)) {
            toolIdss = toolPartRespository.selectByRecordIdReload(recordIds);
        }
        if (CollectionUtil.isNotEmpty(toolIdss)) {
            ToolPartEntity randomToolPartId = CommonUtil.getRandomElement(toolIdss);
            toolPartRespository.updateSelectedFlagById(randomToolPartId.getUniqueId(), 1, id, groupId);
            return randomToolPartId.getUniqueId();
        }
        //从一级库查询
        recordIds = toolPartRespository.selectByRecordReload1(toolType, format, WarehouseConstant.FIRST_TOOL_CABINET);
        if (CollectionUtil.isEmpty(recordIds)) {
            return "";
        }
        List<ToolPartEntity> toolIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recordIds)) {
            toolIds = toolPartRespository.selectByRecordIdReload(recordIds);
        }
        if (CollectionUtil.isNotEmpty(toolIds)) {
            ToolPartEntity randomToolPartId = CommonUtil.getRandomElement(toolIds);
            toolPartRespository.updateSelectedFlagById(randomToolPartId.getUniqueId(), 1, id , groupId);
            return randomToolPartId.getUniqueId();
        }
        return "";
    }

    @Transactional
    public synchronized Object selectByRecordReload1(String toolType, Integer id , String groupId) {
        //加上类型型号的校验
        QueryWrapper<ToolForkInfoEntity> toolForkWrapper = new QueryWrapper<>();
        toolForkWrapper.eq("idnr" , toolType);
        List<ToolForkInfoEntity> toolForkInfoEntities = toolForkInfoMapper.selectList(toolForkWrapper);
        if (CollectionUtil.isEmpty(toolForkInfoEntities)) {
            return "1";
        }
        String partno = toolForkInfoEntities.get(0).getPartno();

        Integer cycleRecordTime = Integer.parseInt(SystemInit.configurationMap.getOrDefault("cycleRecordTime" , 1440).toString());
        Date configureDate = CommonUtil.getTimeBeforeConfigure(cycleRecordTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(configureDate);
        List<ToolPartEntity> toolIdss = toolPartRespository.selectByRecordReload2(partno ,format ,  Arrays.asList(WarehouseConstant.INTELLIGENT_TOOL_CABINET , WarehouseConstant.FIRST_TOOL_CABINET));

        //分组
        Map<String , List<ToolPartEntity>> groupByWarehouseTypeMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(toolIdss)){
            groupByWarehouseTypeMap = toolIdss.stream().collect(Collectors.groupingBy(ToolPartEntity::getWarehouseType));
            if(CollectionUtil.isNotEmpty(groupByWarehouseTypeMap)){
                ToolPartEntity randomToolPartId = null;
                if(groupByWarehouseTypeMap.containsKey("A002")){
                    randomToolPartId = CommonUtil.getRandomElement(groupByWarehouseTypeMap.getOrDefault("A002" , new ArrayList<>()));
                }else if(!groupByWarehouseTypeMap.containsKey("A002") && groupByWarehouseTypeMap.containsKey("A001")){
                    randomToolPartId = CommonUtil.getRandomElement(groupByWarehouseTypeMap.getOrDefault("A001" , new ArrayList<>()));
                }
                toolPartRespository.updateSelectedFlagById(randomToolPartId.getUniqueId(), 1, id, groupId);
                return randomToolPartId.getUniqueId();
            }
        }
//
//        if (CollectionUtil.isNotEmpty(toolIdss)) {
//            ToolPartEntity randomToolPartId = CommonUtil.getRandomElement(toolIdss);
//            toolPartRespository.updateSelectedFlagById(randomToolPartId.getUniqueId(), 1, id);
//            return randomToolPartId.getUniqueId();
//        }
        return "";
    }

    public Object selectUnSelectedList(UnselectedReq unselectedReq) {
        PageHelper.startPage(unselectedReq.getPageNum(), unselectedReq.getPageSize());
        PageInfo<ToolPartEntity> pageInfo = new PageInfo<>(toolPartRespository.selectUnSelectedList(unselectedReq));
        if (CollectionUtil.isNotEmpty(pageInfo.getList())) {
            pageInfo.getList().forEach(toolPartEntity -> {
                if (ObjectUtil.isNotNull(toolPartEntity.getSelectedTaskId())) {
                    MachineToolTaskEntity machineToolTaskEntity = machineToolTaskRespository.selectById(toolPartEntity.getSelectedTaskId());
                    if (ObjectUtil.isNotNull(machineToolTaskEntity)) {
                        toolPartEntity.setMachineTaskName("生产订单号" + machineToolTaskEntity.getOrderTaskId()//工单号
                                + "-" + "工序序号:" + machineToolTaskEntity.getOrderSnapshotCraftSeq()//工单工序号
                                + "-" + "工序名:" + machineToolTaskEntity.getCraftName());//工序名
                    }
                }
            });
        }
        return new PageResult<>(pageInfo.getList(), pageInfo.getTotal());
    }

    public Object updateUnselectedFlag(String id, Integer flag) {
        toolPartRespository.updateSelectedFlagByIds(id, flag);
        return Boolean.TRUE;
    }

    public Object getWarehouseByToolNo(String toolNo, String warehouseType) {
        return inventoryLocationRespository.getWarehouseByToolNo(toolNo, warehouseType);
    }

    public Object qryNnSelectedAssemblyTool(String toolNo) {
        List<UnselectedAssemblyToolVo> resultList = toolPartRespository.qryNnSelectedAssemblyTool(toolNo);
        return resultList;
    }

//    public Object inboundToolPartAssemblyToolReload(InboundToolPartAssemblyToolReloadReq inboundToolPartAssemblyToolReloadReq) throws ToolLifeCycleException {
//        if(CollectionUtil.isNotEmpty(inboundToolPartAssemblyToolReloadReq.getToolPartUniqueIds())){
//            throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_PART_UNIQUE_ID_IS_EMPTY.getCode() , ToolLifeCycleEx.TOOL_PART_UNIQUE_ID_IS_EMPTY.getMsg());
//        }
//        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(inboundToolPartAssemblyToolReloadReq.getToolNo());
//        //向关系表里面插入记录
//        ToolInventoryLocationEntity toolInventoryLocationEntity = insertToolInventoryLocation(inboundToolPartAssemblyToolReloadReq.getNumber(), inboundToolPartAssemblyToolReloadReq.getInventoryLocationId(), assemblyToolInventoryEntity);
//        //查询是否需要出库
//        List<ToolPartEntity> toolPartEntities = queryLocationIdToOutbound(inboundToolPartAssemblyToolReloadReq.getToolPartUniqueIds(), inboundToolPartAssemblyToolReloadReq.getOperator());
//        //生成唯一编号(库位选择)
//        List<ToolPartEntity> toolPartEntityList = toolPartService.buildAssemblyToolPartReload(toolInventoryLocationEntity, inboundToolPartAssemblyToolReloadReq.getNumber() , inboundToolPartAssemblyToolReloadReq.getOperator(), assemblyToolInventoryEntity, toolPartEntities);
//        //生成入库记录
//        List<Integer> toolPartIdList = toolPartEntityList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
//        entryExitRecordService.createEntryRecord(toolInventoryLocationEntity, inboundToolPartAssemblyToolReloadReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, inboundToolPartAssemblyToolReloadReq.getOperator(), inboundToolPartAssemblyToolReloadReq.getBz(), "", "", new Date());
//        return null;
//    }

    @Transactional
    public synchronized Object inboundToolPartAssemblyToolReload(InboundToolPartAssemblyToolReloadReq inboundToolPartAssemblyToolReloadReq) throws ToolLifeCycleException {
        checkIsAssembled(Stream.concat(inboundToolPartAssemblyToolReloadReq.getToolUniqueIds().stream(), inboundToolPartAssemblyToolReloadReq.getShankUniqueIds().stream()).collect(Collectors.toList()));
        AssemblyToolInventoryEntity assemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(inboundToolPartAssemblyToolReloadReq.getToolNo());
        //向关系表里面插入记录
        ToolInventoryLocationEntity toolInventoryLocationEntity = insertToolInventoryLocation(inboundToolPartAssemblyToolReloadReq.getNumber(), inboundToolPartAssemblyToolReloadReq.getInventoryLocationId(), assemblyToolInventoryEntity);
        if (ObjectUtil.isNull(toolInventoryLocationEntity)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        //出库零件记录保存
        List<ToolPartEntity> outboundToolList = toolPartService.getByUniqueIds(inboundToolPartAssemblyToolReloadReq.getToolUniqueIds());
        List<ToolPartEntity> outboundShankList = toolPartService.getByUniqueIds(inboundToolPartAssemblyToolReloadReq.getShankUniqueIds());
        if (CollectionUtil.isEmpty(outboundShankList) || CollectionUtil.isEmpty(outboundToolList)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        if (outboundToolList.size() < inboundToolPartAssemblyToolReloadReq.getToolUniqueIds().size() || outboundShankList.size() < inboundToolPartAssemblyToolReloadReq.getShankUniqueIds().size()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        queryLocationIdToOutboundReload(Stream.concat(outboundToolList.stream(), outboundShankList.stream()).collect(Collectors.toList()), inboundToolPartAssemblyToolReloadReq.getOperator());
        //生成唯一编号(库位选择)
        List<ToolPartEntity> toolPartEntityList = toolPartService.buildAssemblyToolPartReload(toolInventoryLocationEntity, inboundToolPartAssemblyToolReloadReq.getNumber(), inboundToolPartAssemblyToolReloadReq.getToolUniqueIds().size(), inboundToolPartAssemblyToolReloadReq.getShankUniqueIds().size(), inboundToolPartAssemblyToolReloadReq.getOperator(), assemblyToolInventoryEntity, outboundToolList, outboundShankList);
        String toolPartParams = buildToolPartParams(toolPartEntityList.get(0));
        //生成入库记录
        List<Integer> toolPartIdList = toolPartEntityList.stream().map(ToolPartEntity::getId).collect(Collectors.toList());
        entryExitRecordService.createEntryRecordReload(toolInventoryLocationEntity, inboundToolPartAssemblyToolReloadReq.getNumber(), toolPartIdList, CommonConstant.INBOUND_CONST, inboundToolPartAssemblyToolReloadReq.getOperator(), inboundToolPartAssemblyToolReloadReq.getBz(), "", "", new Date(), toolPartParams);
        return toolPartEntityList.stream().map(ToolPartEntity::getUniqueId).collect(Collectors.toList());
    }

    private void checkIsAssembled(List<String> uniqueIds) throws ToolLifeCycleException {
        if (CollectionUtil.isEmpty(uniqueIds)) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        List<ToolPartEntity> byUniqueIds = toolPartService.getByUniqueIds(uniqueIds);
        if (CollectionUtil.isEmpty(uniqueIds) || CollectionUtil.isEmpty(byUniqueIds) || uniqueIds.size() != byUniqueIds.size()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        for (ToolPartEntity byUniqueId : byUniqueIds) {
            if(ObjectUtil.isNull(byUniqueId.getIsAssembled()) || (ObjectUtil.isNotNull(byUniqueId.getIsAssembled()) && byUniqueId.getIsAssembled() != 0)){
                throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
            }
        }
    }

    public synchronized Object buildAssemblyTool(List<String> toolUniqueIds, List<String> shankUniqueIds, String originalToolNo, String newToolNo, String operator) throws ToolLifeCycleException {
        //出库零件记录保存
        List<ToolPartEntity> outboundToolList = toolPartService.getByUniqueIds(toolUniqueIds);
        List<ToolPartEntity> outboundShankList = toolPartService.getByUniqueIds(shankUniqueIds);
        if (CollectionUtil.isEmpty(outboundShankList) || outboundToolList.size() < toolUniqueIds.size()
                || CollectionUtil.isEmpty(outboundToolList) || outboundShankList.size() < shankUniqueIds.size()) {
            throw new ToolLifeCycleException(ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getCode(), ToolLifeCycleEx.INVENTORY_DATA_EXCEPTION.getMsg());
        }
        AssemblyToolInventoryEntity newAssemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(newToolNo);
        //校验库存总成类型
        if (ObjectUtil.isNotNull(newAssemblyToolInventoryEntity)) {
            List<String> toolIdnrs = outboundToolList.stream().map(ToolPartEntity::getIdnr).distinct().collect(Collectors.toList());
            List<String> shankIdnrs = outboundShankList.stream().map(ToolPartEntity::getIdnr).distinct().collect(Collectors.toList());
            if (!(StringUtils.isNotBlank(newAssemblyToolInventoryEntity.getToolType()) && CollectionUtil.isNotEmpty(toolIdnrs) && toolIdnrs.contains(newAssemblyToolInventoryEntity.getToolType()))
                    || !(StringUtils.isNotBlank(newAssemblyToolInventoryEntity.getShankType()) && CollectionUtil.isNotEmpty(shankIdnrs) && shankIdnrs.contains(newAssemblyToolInventoryEntity.getShankType()))) {
                throw new ToolLifeCycleException(ToolLifeCycleEx.TOOL_NO_CONFLICT.getCode(), ToolLifeCycleEx.TOOL_NO_CONFLICT.getMsg());
            }
        } else {
            AssemblyToolInventoryEntity originalAssemblyToolInventoryEntity = queryOneAssemblyToolInventoryEntity(originalToolNo);
            newAssemblyToolInventoryEntity = new AssemblyToolInventoryEntity();
            BeanUtils.copyProperties(originalAssemblyToolInventoryEntity, newAssemblyToolInventoryEntity);
            newAssemblyToolInventoryEntity.setId(null);
            assemblyToolInventoryMapper.insert(newAssemblyToolInventoryEntity);
        }

        queryLocationIdToOutboundReload(Stream.concat(outboundToolList.stream(), outboundShankList.stream()).collect(Collectors.toList()), operator);
        //生成唯一编号(库位选择)
        List<ToolPartEntity> toolPartEntityList = toolPartService.buildAssemblyTool(0, 1, toolUniqueIds.size(), shankUniqueIds.size(), operator, newAssemblyToolInventoryEntity, outboundToolList, outboundShankList);
        return toolPartEntityList.stream().map(ToolPartEntity::getUniqueId).collect(Collectors.toList());
    }

    private List<ToolPartEntity> queryLocationIdToOutbound(List<String> asList, String operator) {
        List<ToolPartEntity> toolPartEntities = new ArrayList<>();
        asList.forEach(uniqueId -> {
            QueryWrapper<ToolPartEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("unique_id", uniqueId);
            ToolPartEntity toolPartEntity = toolPartMapper.selectOne(wrapper);
            if (ObjectUtil.isNull(toolPartEntity)) {
                return;
            }
            if (ObjectUtil.isNotNull(toolPartEntity) && ObjectUtil.isNotNull(toolPartEntity.getInventoryLocationId()) && toolPartEntity.getInventoryLocationId() > 0) {
                //执行刀柄出库操作
                InboundUniqueToolReq inboundUniqueToolReq = new InboundUniqueToolReq();
                inboundUniqueToolReq.setInboundToolUniqueIds(Arrays.asList(toolPartEntity.getUniqueId()));
                inboundUniqueToolReq.setLocationId(toolPartEntity.getInventoryLocationId());
                inboundUniqueToolReq.setPartno(toolPartEntity.getPartno());
                inboundUniqueToolReq.setOperator(operator);
                try {
                    outboundUniqueTool(inboundUniqueToolReq);
                } catch (ToolLifeCycleException e) {
                    log.error(e.getMessage());
                }
            }
            toolPartEntities.add(toolPartEntity);
        });
        return toolPartEntities;
    }

    private List<ToolPartEntity> queryLocationIdToOutboundReload(List<ToolPartEntity> asList, String operator) {
        List<ToolPartEntity> toolPartEntities = new ArrayList<>();
        asList.forEach(toolPartEntity -> {
            if (ObjectUtil.isNotNull(toolPartEntity) && ObjectUtil.isNotNull(toolPartEntity.getInventoryLocationId()) && toolPartEntity.getInventoryLocationId() > 0) {
                //执行刀柄出库操作
                InboundUniqueToolReq inboundUniqueToolReq = new InboundUniqueToolReq();
                inboundUniqueToolReq.setInboundToolUniqueIds(Arrays.asList(toolPartEntity.getUniqueId()));
                inboundUniqueToolReq.setLocationId(toolPartEntity.getInventoryLocationId());
                inboundUniqueToolReq.setPartno(toolPartEntity.getPartno());
                inboundUniqueToolReq.setOperator(operator);
                try {
                    outboundUniqueTool(inboundUniqueToolReq);
                } catch (ToolLifeCycleException e) {
                    log.error(e.getMessage());
                }
            }
            toolPartEntities.add(toolPartEntity);
        });
        return toolPartEntities;
    }

    public Object test() {
        List<InventoryLocationEntity> updateList = new ArrayList<>();
        List<ToolInventoryLocationEntity> groupByLocationId = toolInventoryLocationRespository.countByInventoryLocationId();
        //List<ToolInventoryLocationEntity> toolInventoryLocationEntities = toolInventoryLocationMapper.selectList(new QueryWrapper<>());
        List<InventoryLocationEntity> inventoryLocationEntities = inventoryLocationRespository.selectAllList();
        groupByLocationId.forEach(toolInventoryLocationEntity -> {
            inventoryLocationEntities.forEach(inventoryLocationEntity -> {
                if (Objects.equals(inventoryLocationEntity.getId(), toolInventoryLocationEntity.getInventoryLocationId()) && toolInventoryLocationEntity.getPhysicalInventory() > 0) {
                    inventoryLocationEntity.setUseCapacity(toolInventoryLocationEntity.getPhysicalInventory());
                    inventoryLocationRespository.updateCapacityById(inventoryLocationEntity);
                }
            });
        });
        return Boolean.TRUE;
    }

    public Object importIToolCabinetStockReload(List<IToolCabinetStockImport> importData) {
        List<ToolForkInfoEntity> updateList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(importData)) {
            importData = importData
                    .stream()
                    .filter(distinctByKey(IToolCabinetStockImport::getPartno))
                    .collect(Collectors.toList());
        }
        importData.forEach(iToolCabinetStockImport -> {
            QueryWrapper<ToolForkInfoEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("partno", iToolCabinetStockImport.getPartno());
            ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(wrapper);
            if (ObjectUtil.isNotNull(toolForkInfoEntity) && !toolForkInfoEntity.getIdnr().equals(iToolCabinetStockImport.getType())) {
                toolForkInfoEntity.setIdnr(iToolCabinetStockImport.getType());
                toolForkInfoEntity.setPartType(iToolCabinetStockImport.getType());
                updateList.add(toolForkInfoEntity);

                QueryWrapper<ToolPartEntity> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("partno", iToolCabinetStockImport.getPartno());
                List<ToolPartEntity> updateToolList = toolPartMapper.selectList(wrapper1);
                if (CollectionUtil.isNotEmpty(updateToolList)) {
                    updateToolList.forEach(toolPartEntity -> {
                        toolPartEntity.setIdnr(iToolCabinetStockImport.getType());
                    });
                    toolPartMapper.updateBatchById(updateToolList);
                }
            }
        });
        if (CollectionUtil.isNotEmpty(updateList)) {
            toolForkInfoMapper.updateBatchById(updateList);
        }
        return Boolean.TRUE;
    }

    public Object qryEquipmentNameById(Integer id) {
        return inventoryLocationRespository.qryEquipmentNameById(id);
    }

    public void exportWarehouseTemplate(HttpServletResponse response) throws IOException {
        String outputFileName = "货架导入模版.xlsx";
        //ToolUsageReportExport toolUsageReportExport = buildToolUsageReport(taskId);
        CommonUtil.exportExcelFile(new Object(), "/template/货架导入模版.xlsx", response, outputFileName);
    }

    private void writeData(ExcelWriter excelWriter) {
        WriteSheet writeSheet = new WriteSheet();
        //设置写到第几个sheet
        writeSheet.setSheetNo(0);
        writeSheet.setSheetName("货架导入模板");
        //设置表头
        List<List<String>> headList = new ArrayList<>();
        String orderName = "生产订单";
        String planName = "计划信息";
        headList.add(Arrays.asList(orderName, "生产订单"));
        headList.add(Arrays.asList(orderName, "物料编码"));
        headList.add(Arrays.asList(orderName, "物料型号"));
        headList.add(Arrays.asList(planName, "物料名称"));
        headList.add(Arrays.asList(planName, "计划数量"));
        headList.add(Arrays.asList(planName, "创建日期"));
        headList.add(Arrays.asList(planName, "交货日期"));
        headList.add(Arrays.asList(planName, "优先级"));
        headList.add(Arrays.asList(planName, "备注"));
        writeSheet.setHead(headList);
        //（设置数据）
        //第一列序号从1开始增加
        ArrayList<Object> dataList = new ArrayList<>();
        excelWriter.write(dataList, writeSheet);
    }

    public void importWarehouseTemplate(List<WarehouseImportEntity> importData) {
        List<WarehouseEntity> insertList = new ArrayList<>();
        List<String> existNameList = warehouseRespository.selectAll();
        if (CollectionUtil.isNotEmpty(importData)) {
            importData = importData
                    .stream()
                    .filter(distinctByKey(WarehouseImportEntity::getWarehouseName)).collect(Collectors.toList());
            importData = importData
                    .stream()
                    .filter(warehouseImportEntity -> !existNameList.contains(warehouseImportEntity.getWarehouseName())).collect(Collectors.toList());
            importData.forEach(warehouseImportEntity -> {
                WarehouseEntity warehouseEntity = new WarehouseEntity();
                warehouseEntity.setGoodsAreaName(warehouseImportEntity.getGoodAreaName());
                warehouseEntity.setName(warehouseImportEntity.getWarehouseName());
                warehouseEntity.setColumn(warehouseImportEntity.getWarehouseColumn());
                warehouseEntity.setRow(warehouseImportEntity.getWarehouseRow());
                warehouseEntity.setUseCapacity(0);
                warehouseEntity.setTotalCapacity(ObjectUtil.isNotNull(warehouseImportEntity.getCapacity()) ? warehouseImportEntity.getCapacity() : 2000);
                warehouseEntity.setStatus("2");
                if (ObjectUtil.isNotNull(warehouseImportEntity.getWarehouseType()) && warehouseImportEntity.getWarehouseType() == 1) {
                    warehouseEntity.setType("A001");
                } else if (ObjectUtil.isNotNull(warehouseImportEntity.getWarehouseType()) && warehouseImportEntity.getWarehouseType() == 2) {
                    warehouseEntity.setType("A002");
                } else if (ObjectUtil.isNotNull(warehouseImportEntity.getWarehouseType()) && warehouseImportEntity.getWarehouseType() == 3) {
                    warehouseEntity.setType("A003");
                } else if (ObjectUtil.isNotNull(warehouseImportEntity.getWarehouseType()) && warehouseImportEntity.getWarehouseType() == 4) {
                    warehouseEntity.setType("A004");
                } else if (ObjectUtil.isNotNull(warehouseImportEntity.getWarehouseType()) && warehouseImportEntity.getWarehouseType() == 5) {
                    warehouseEntity.setType("A005");
                }
                insertList.add(warehouseEntity);
            });
        }
        if (CollectionUtil.isNotEmpty(insertList)) {
            warehouseRespository.insertBatch(insertList);
        }
    }

    public void exportInventoryLocationTemplate(HttpServletResponse response) throws IOException {
        String outputFileName = "库位导入模版.xlsx";
        //ToolUsageReportExport toolUsageReportExport = buildToolUsageReport(taskId);
        CommonUtil.exportExcelFile(new Object(), "/template/库位导入模版.xlsx", response, outputFileName);
    }

    public void importLocationTemplate(List<LocationImportEntity> importData) {
        List<InventoryLocationEntity> insertList = new ArrayList<>();
        List<WarehouseNameVo> existNameList = warehouseRespository.selectAllReload();
        Map<String, Integer> nameIdMap = existNameList
                .stream()
                .collect(Collectors.toMap(WarehouseNameVo::getWarehouseName, WarehouseNameVo::getWarehouseId));
        if (CollectionUtil.isNotEmpty(importData)) {
            importData = importData
                    .stream()
                    .filter(distinctByKey(LocationImportEntity::getLocationNum))
                    .collect(Collectors.toList());
            importData = importData
                    .stream()
                    .filter(locationImportEntity -> ObjectUtil.isNotNull(nameIdMap.get(locationImportEntity.getWarehouseName())))
                    .collect(Collectors.toList());
            importData.forEach(locationImportEntity -> {
                InventoryLocationEntity inventoryLocationEntity = new InventoryLocationEntity();
                inventoryLocationEntity.setWarehouseName(locationImportEntity.getWarehouseName());
                inventoryLocationEntity.setRow(locationImportEntity.getLocationRow());
                inventoryLocationEntity.setColumn(locationImportEntity.getLocationColumn());
                inventoryLocationEntity.setUseCapacity(0);
                inventoryLocationEntity.setCapacity(locationImportEntity.getTotalCapacity());
                inventoryLocationEntity.setStatus(2);
                inventoryLocationEntity.setWarehouseId(nameIdMap.get(locationImportEntity.getWarehouseName()));
                inventoryLocationEntity.setLocationNum(locationImportEntity.getLocationNum());
                inventoryLocationEntity.setLastUpdateTime(new Date());
                //设置param参数
                inventoryLocationEntity.setParams(JSONArray.toJSONString(Arrays.toString(locationImportEntity.getLocationNum().split("\\/"))));
                insertList.add(inventoryLocationEntity);
            });
        }
        if (CollectionUtil.isNotEmpty(insertList)) {
            inventoryLocationRespository.insertBatch(insertList);
        }
    }

    public Object toolReturnIndexReload(ToolReturnIndexReq toolReturnIndexReq) {
        //查询已写入过且没有组成总成的刀柄
        ToolConsumptionandUsageAnalysisReq toolConsumptionandUsageAnalysisReq = new ToolConsumptionandUsageAnalysisReq();
        if (StringUtil.isNotEmpty(toolReturnIndexReq.getLocationNum())) {
            toolConsumptionandUsageAnalysisReq.setLocationNum(toolReturnIndexReq.getLocationNum());
        }
        if (StringUtil.isNotEmpty(toolReturnIndexReq.getWarehouseType())) {
            toolConsumptionandUsageAnalysisReq.setWarehouseType(toolReturnIndexReq.getWarehouseType());
        }
        if (ObjectUtil.isNotEmpty(toolReturnIndexReq.getWarehouseId())) {
            toolConsumptionandUsageAnalysisReq.setWarehouseId(toolReturnIndexReq.getWarehouseId());
        }
        List<Integer> inventoryLocationIds = new ArrayList<>();
        if (StringUtil.isNotEmpty(toolReturnIndexReq.getLocationNum()) || StringUtil.isNotEmpty(toolReturnIndexReq.getWarehouseType()) || ObjectUtil.isNotEmpty(toolReturnIndexReq.getWarehouseId())) {
            inventoryLocationIds = inventoryLocationRespository.selectLocationIdByLocationNum(toolConsumptionandUsageAnalysisReq);
        }
        toolReturnIndexReq.setInventoryLocationIds(inventoryLocationIds);
        List<ToolPartEntity> toolPartEntities = toolPartRespository.toolReturnIndexReload(toolReturnIndexReq);
        if (CollectionUtil.isNotEmpty(toolPartEntities)) {
            toolPartEntities.forEach(toolPartEntity -> {
                if (ObjectUtil.isNotNull(toolPartEntity) && ObjectUtil.isNotNull(toolPartEntity.getInventoryLocationId()) && toolPartEntity.getInventoryLocationId() > 0) {
                    LocationNameVo locationNameVo = inventoryLocationRespository.queryLocationByInventoryLocationId(toolPartEntity.getInventoryLocationId());
                    if (locationNameVo != null) {
                        StringBuilder stringBuilder = new StringBuilder();
                        String locationName = stringBuilder.append(locationNameVo.getTypeName()).append("-").append(locationNameVo.getWarehouseName()).append("-库位").append(locationNameVo.getLocationNum()).append("-位置").append(locationNameVo.getRow()).append("-").append(locationNameVo.getColumn()).toString();
                        toolPartEntity.setWarehouseName(locationName);
                    }
                }
            });
        }
        return toolPartEntities;
    }

    public Object getWarehouseSum() {
        List<LocationIdVo>  locationIdVos =  inventoryLocationRespository.selectLocationIdList();
        List<WarehouseTypeNumberVo> resultlist = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(locationIdVos)){
            Map<String , List<LocationIdVo>> groupByWarehouseTypeMap  = locationIdVos
                    .stream()
                    .filter(locationIdVo -> StringUtils.isNotBlank(locationIdVo.getWarehouseType()))
                    .collect(Collectors.groupingBy(LocationIdVo::getWarehouseType));
            if(CollectionUtil.isNotEmpty(warehouseTypeMap)){
                for (Map.Entry<String, String> warehouseTypeNameEntry : warehouseTypeMap.entrySet()) {
                    List<LocationIdVo> warehouseTypelocationIdVos = groupByWarehouseTypeMap.get(warehouseTypeNameEntry.getKey());
                    if(CollectionUtil.isNotEmpty(warehouseTypelocationIdVos)){
                        Integer countNumber =  toolPartRespository.selectCountByLocationIds(warehouseTypelocationIdVos
                                .stream()
                                .map(LocationIdVo::getLocationId)
                                .collect(Collectors.toList()));
                        if(ObjectUtil.isNotNull(countNumber) && countNumber > 0){
                            WarehouseTypeNumberVo warehouseTypeNumberVo = new WarehouseTypeNumberVo();
                            warehouseTypeNumberVo.setName(warehouseTypeMap.get(warehouseTypeNameEntry.getKey()));
                            warehouseTypeNumberVo.setNumber(countNumber);
                            resultlist.add(warehouseTypeNumberVo);
                        }
                    }
                }
            }
        }
        return resultlist;
    }

    public Object getToolDamageReport(ToolDamageReportReq toolDamageReportReq) {
        List<ToolDamageReportVo> resultList =  toolPartRespository.selectToolDamageReport(toolDamageReportReq);
        List<ToolDamageReportVo> pageList =  new ArrayList<>();
//        List<ToolPartEntity> updateList =  new ArrayList<>();
        if(CollectionUtil.isNotEmpty(resultList)){
            resultList.forEach(toolDamageReportVo -> {
                if(StringUtils.isNotBlank(toolDamageReportVo.getDamageLog()) || !toolDamageReportVo.getDamageLog().equals("[]")){
                    List<AssemblyDamageLogVo> damageLogVos = JSONArray.parseArray(toolDamageReportVo.getDamageLog() , AssemblyDamageLogVo.class);
                    if(CollectionUtil.isNotEmpty(damageLogVos)){
                        toolDamageReportVo.setOperator(damageLogVos.get(0).getOperator());
                    }
//                    ToolPartEntity toolPartEntity = new ToolPartEntity();
//                    BeanUtils.copyProperties(toolDamageReportVo , toolPartEntity);
//                    updateList.add(toolPartEntity);
                }
            });
            //根据人员过滤
            if(StringUtils.isNotBlank(toolDamageReportReq.getOperator())){
                resultList = resultList.stream().filter(toolDamageReportVo -> StringUtils.isNotBlank(toolDamageReportVo.getOperator()) && toolDamageReportVo.getOperator().contains(toolDamageReportReq.getOperator())).collect(Collectors.toList());
            }
        }
        if(CollectionUtil.isNotEmpty(resultList)){
            pageList = CommonUtil.pageList(resultList , toolDamageReportReq.getPageNum() , toolDamageReportReq.getPageSize());
        }
//        if(CollectionUtil.isNotEmpty(updateList)){
//            toolPartMapper.updateBatchById(updateList);
//        }
        return new PageResult<>(pageList.stream().sorted(Comparator.comparing(ToolDamageReportVo::getDamageTime)).collect(Collectors.toList()), (long)resultList.size());
    }

    public Object getToolDamageReportIndex(ToolDamageReportReq toolDamageReportReq) {
        List<ToolDamageReportVo> baseDataList =  toolPartRespository.selectToolDamageReport(toolDamageReportReq);
        List<ToolDamageReportIndexVo> groupList =  new ArrayList<>();
        Map<String , List<ToolDamageReportVo>> groupByToolNoMap = new HashMap<>();
        List<ToolDamageReportIndexVo> pageList =  new ArrayList<>();
        if(CollectionUtil.isNotEmpty(baseDataList)){
            //根据刀号分组整合数据
            groupByToolNoMap = baseDataList.stream().collect(Collectors.groupingBy(ToolDamageReportVo::getToolNo));
            if(CollectionUtil.isNotEmpty(groupByToolNoMap)){
                for (Map.Entry<String, List<ToolDamageReportVo>> toolNoDamageVoListEntry : groupByToolNoMap.entrySet()) {
                    ToolDamageReportIndexVo toolDamageReportIndexVo = new ToolDamageReportIndexVo();
                    toolDamageReportIndexVo.setToolNo(toolNoDamageVoListEntry.getKey());
                    toolDamageReportIndexVo.setNumber(toolNoDamageVoListEntry.getValue().size());
                    groupList.add(toolDamageReportIndexVo);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(groupList)){
            pageList = CommonUtil.pageList(groupList , toolDamageReportReq.getPageNum() , toolDamageReportReq.getPageSize());
            if(CollectionUtil.isNotEmpty(pageList)){
                pageList.forEach(toolDamageReportIndexVo -> toolDamageReportIndexVo.setType(assemblyToolInventoryRepository.selectTypeByToolNo(toolDamageReportIndexVo.getToolNo())));
            }
        }
        return new PageResult<>(pageList , (long)groupList.size());
    }

    public Object test1() {
        QueryWrapper<EntryExitRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("tool_no");
        wrapper.eq("type" , "inbound");
        wrapper.eq("warehouse_type" , "A003");
        List<EntryExitRecordEntity> entryExitRecordEntities = entryExitRecordMapper.selectList(wrapper);
        List<EntryExitRecordEntity> updateList = new ArrayList<>();
        entryExitRecordEntities.forEach(entryExitRecordEntity -> {
            QueryWrapper<AssemblyToolInventoryEntity> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("tool_no" , entryExitRecordEntity.getToolNo());
            AssemblyToolInventoryEntity assemblyToolInventoryEntity = assemblyToolInventoryMapper.selectOne(wrapper1);
            if(ObjectUtil.isNotNull(assemblyToolInventoryEntity)){
                List<ToolForkInfoEntity> toolForkInfoEntities1 = toolForkRespository.selectPartnoByIdnr(assemblyToolInventoryEntity.getShankType());
                List<ToolForkInfoEntity> toolForkInfoEntities2 = toolForkRespository.selectPartnoByIdnr(assemblyToolInventoryEntity.getShankType());

                List<ToolForkInfoCountVo> list = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(toolForkInfoEntities1)){
                    ToolForkInfoCountVo toolForkCountVo = new ToolForkInfoCountVo();
                    toolForkCountVo.setPartno(toolForkInfoEntities1.get(0).getPartno());
                    toolForkCountVo.setNumber(1);
                    list.add(toolForkCountVo);
                }
                if(CollectionUtil.isNotEmpty(toolForkInfoEntities2)){
                    ToolForkInfoCountVo toolForkCountVo1 = new ToolForkInfoCountVo();
                    toolForkCountVo1.setPartno(toolForkInfoEntities2.get(0).getPartno());
                    toolForkCountVo1.setNumber(1);
                    list.add(toolForkCountVo1);
                }
                entryExitRecordEntity.setToolParams(JSONArray.toJSONString(list));
                updateList.add(entryExitRecordEntity);
            }
        });
        if(CollectionUtil.isNotEmpty(updateList)){
            entryExitRecordMapper.updateBatchById(updateList);
        }
        return Boolean.TRUE;
    }


//    public Object toolReturnDetail(String uniqueId) {
//        return toolPartRespository.selectList(uniqueId);
//    }

}

